How to add css and js files on node pages independ

2019-07-30 16:53发布

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 ?

2条回答
Fickle 薄情
2楼-- · 2019-07-30 17:16

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

查看更多
戒情不戒烟
3楼-- · 2019-07-30 17:28

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.

查看更多
登录 后发表回答