drupal_add_css, drupal_add_js does not work

前端 未结 3 2063
南笙
南笙 2021-01-15 05:15

I am using drupal_add_css() and drupal_add_js() to add CSS and JavaScript files to my Drupal site. I am doing this in a module called control so th

3条回答
  •  迷失自我
    2021-01-15 05:20

    The reason these functions aren't working within the preprocess_page() function is that template_preprocess_page() (which is called first) has already formatted the structured content into variables $scripts and $styles. If you want to add additional js or css at the preprocess level, you need to regenerate those 2 variables, something like this:

    function control_preprocess_page(&$vars) {
      // Add new CSS.
      drupal_add_css('path/to/css/foo.css');
      // Rebuild the 'styles variable.
      $vars['styles'] = drupal_get_css();
    
      // Add new JS.
      drupal_add_js(...);
      $vars['scripts'] = drupal_get_js();
    }
    

    Using drupal_add_js/drupal_add_css in hook_init, or a more precisely targeted function (eg, an alter hook, or nodeapi hook, if applicable), will avoid having to regenerate those variables.

提交回复
热议问题