How to add css and js files on node pages independent of the theme?

走远了吗. 提交于 2019-12-11 05:21:36

问题


I am using display suite to display a full node of type 'Article'. I want to add some css and js on the page containing the article node, though the adding of these can't be dependent on the themeing. So I cannot use the template.php file

How would I be able to do this ?


回答1:


Create a new module and put it in: /sites/all/modules/custom

The module structure and files would look like this:

ahelper/
ahelper/css/article_node.css
ahelper/js/article_node.js
ahelper/ahelper.info
ahelper/ahelper.module

ahelper/ahelper.info

core = "7.x"
name = "Article Helper"
project = "ahelper"
version = "7.x-1.0"

ahelper/ahelper.module

<?php
/**
 * Implements hook_node_view()
 */
function ahelper_node_view($node, $view_mode, $langcode) {
  // if node is an article, and we're looking at a full page view
  if ($node->type == 'article' && $view_mode == 'full') {
    // then add this javascript file
    drupal_add_js(drupal_get_path('module', 'ahelper') .'/js/article_node.js');
    // and add this css file
    drupal_add_css(drupal_get_path('module', 'ahelper') .'/css/article_node.css');
  }
}

Then just enable the module. You can play around with the node_view hook.




回答2:


Create a custom module and include your js and css files using the functions drupal_add_js and drupal_add_css. You can call them either in your custom module's hook_init or hook_nodeapi (or Node Api Hooks in Drupal 7) depending on how you want to include your files. These functions get called regardless of what theme your using.

References: http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_js

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_css



来源:https://stackoverflow.com/questions/8295498/how-to-add-css-and-js-files-on-node-pages-independent-of-the-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!