[英]Add js to a template file using theme preprocess
I have a custom Drupal 7 module which is hooking into the media module and I'm having trouble with adding some js into its render. 我有一个自定义的Drupal 7模块,该模块已连接到媒体模块,并且在向其渲染器中添加一些js时遇到了麻烦。
The module is defining a theme like this: 该模块正在定义这样的主题:
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',
)
);
}
And my formatter (view) is returning my element like so: 我的格式化程序(视图)正在返回我的元素,如下所示:
$element = array(
'#theme' => 'media_flash_video',
'#uri' => $file->uri,
'#options' => array(),
);
return $element;
Now, I have a preprocess function which adds some js: 现在,我有一个预处理函数,它添加了一些js:
function media_flash_preprocess_media_flash_video(&$variables) {
$path = libraries_get_path('swfobject');
drupal_add_js($path . '/swfobject.js');
...
}
And also a drupal add js in my template file: 还有在我的模板文件中添加drupal js:
/**
* @file media_flash/includes/themes/media-flash.tpl.php
*/
$javascript = '
(function ($) {
...
})(jQuery);
';
drupal_add_js($javascript, 'inline');
The issue is weird. 这个问题很奇怪。 When I'm logged in then everything works fine, all the time. 登录后,所有时间都可以正常工作。 However, when I am using it as an anonymous user it all works fine the first load (after cache clear) but then the two javascripts arent added anymore. 但是,当我以匿名用户的身份使用它时,第一次加载(清除缓存后)都可以正常工作,但随后又添加了两个javascripts arent。
I have tried to change my preprocess function so it adds the javascript with this $variables['scripts'] = drupal_get_js();
我试图更改我的预处理功能,因此它使用$variables['scripts'] = drupal_get_js();
添加了javascript $variables['scripts'] = drupal_get_js();
but this also has the same behaviour. 但这也具有相同的行为。
Ive googled around a bit and found some suggestions but nothing's worked thus far. Ive在Google上搜索了一下,发现了一些建议,但到目前为止没有任何效果。 Any help is appreciated. 任何帮助表示赞赏。
Thanks, 谢谢,
EDIT: So I looked into this a bit more and the code is being executed through the filter module. 编辑:所以我调查了一下,并且代码正在通过过滤器模块执行。 It seems as though the first time it gets executed it gets cached and then it is just recieved from the cache each time after that, so the drupal_add_js code isn't run again. 好像它是第一次执行时就被缓存了,然后每次都从缓存中被接收到,因此drupal_add_js代码不会再次运行。
Is there a way around this caching or do I need to remove my js from this part all together? 有没有办法解决这种缓存,或者我需要从这部分中一起删除我的js吗?
您始终可以在页面级别“ hook_page_alter (&$ page)”中添加js。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.