簡體   English   中英

使用主題預處理將js添加到模板文件

[英]Add js to a template file using theme preprocess

我有一個自定義的Drupal 7模塊,該模塊已連接到媒體模塊,並且在向其渲染器中添加一些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');

這個問題很奇怪。 登錄后,所有時間都可以正常工作。 但是,當我以匿名用戶的身份使用它時,第一次加載(清除緩存后)都可以正常工作,但隨后又添加了兩個javascripts arent。

我試圖更改我的預處理功能,因此它使用$variables['scripts'] = drupal_get_js();添加了javascript $variables['scripts'] = drupal_get_js(); 但這也具有相同的行為。

Ive在Google上搜索了一下,發現了一些建議,但到目前為止沒有任何效果。 任何幫助表示贊賞。

謝謝,

編輯:所以我調查了一下,並且代碼正在通過過濾器模塊執行。 好像它是第一次執行時就被緩存了,然后每次都從緩存中被接收到,因此drupal_add_js代碼不會再次運行。

有沒有辦法解決這種緩存,或者我需要從這部分中一起刪除我的js嗎?

您始終可以在頁面級別“ hook_page_alter (&$ page)”中添加js。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM