【问题标题】:Add js to a template file using theme preprocess使用主题预处理将 js 添加到模板文件
【发布时间】:2013-05-07 11:07:44
【问题描述】:

我有一个自定义 Drupal 7 模块,它连接到 media 模块,我无法在其渲染中添加一些 js。

该模块正在定义这样的主题:

function media_flash_theme($existing, $type, $theme, $path) {
  return array(
    'media_flash_video' => array(
      'variables' => array('uri' => NULL, 'options' => array()),
      'file' => 'media_flash.theme.inc',
      'path' => $path . '/includes/themes',
      'template' => 'media-flash',
    )
  );
}

我的格式化程序(视图)正在返回我的元素,如下所示:

$element = array(
  '#theme' => 'media_flash_video',
  '#uri' => $file->uri,
  '#options' => array(),
);

return $element;

现在,我有一个预处理函数,它添加了一些 js:

function media_flash_preprocess_media_flash_video(&$variables) {

  $path = libraries_get_path('swfobject');
  drupal_add_js($path . '/swfobject.js');

  ...
}

还有一个drupal在我的模板文件中添加js:

/**
 * @file media_flash/includes/themes/media-flash.tpl.php
 */


$javascript = '
(function ($) {
...
})(jQuery);
';

drupal_add_js($javascript, 'inline');

这个问题很奇怪。当我登录时,一切正常,一直。但是,当我以匿名用户身份使用它时,它在第一次加载(缓存清除后)时一切正常,但随后不再添加两个 javascript。

我尝试更改我的预处理函数,以便添加带有 $variables['scripts'] = drupal_get_js(); 的 javascript,但这也具有相同的行为。

我用谷歌搜索了一下,发现了一些建议,但到目前为止没有任何效果。任何帮助表示赞赏。

谢谢,

编辑:所以我对此进行了更多研究,代码正在通过过滤器模块执行。似乎第一次执行时它会被缓存,然后每次都从缓存中接收它,所以 drupal_add_js 代码不会再次运行。

有没有办法解决这个缓存,还是我需要从这部分一起删除我的 js?

【问题讨论】:

标签: drupal drupal-7 drupal-theming


【解决方案1】:

您可以随时在页面级别“hook_page_alter(&$page)”中添加js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2014-11-23
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多