简体   繁体   中英

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.

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:

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:

/**
 * @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.

I have tried to change my preprocess function so it adds the javascript with this $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. 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.

Is there a way around this caching or do I need to remove my js from this part all together?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM