Drupal 7 - How to assign a variable to a template?

感情迁移 提交于 2019-12-25 07:48:35

问题


So..I have created a module called "moon". In the module, i use moon_menu to assign a menu that calls back moon_page to display something to the browser.

function moon_page(){

$moonsvariable = 'hi this is a function';
return theme('moon_display',$moonsvariable);

}

is it possible to assign a custom variable to the template then use it in the template?

I would like to it in the following way.

function moon_page(){

  $custom_variable = "this is a custom variable";
  $moonsvariable = 'hi this is a function';
  return theme('moon_display',$moonsvariable);

}

Then I like to use <? print $custom_variable ?> in my theme to display it.

I tried variable_set, but it does not work.


回答1:


/*
 * Implementation of hook_theme().
 */
function moon_theme($existing, $type, $theme, $path){
  return array(
    'moon' => array(
      'variables' => array('content' => NULL),
      'file' => 'moon', // place you file in 'theme' folder of you module folder
      'path' => drupal_get_path('module', 'moon') .'/theme'
    )
  );
}

function moon_page(){

  // some code to generate $content variable as array
  $content['data1'] = 'Lorem ipsum';
  $content['data2'] = 'Ipsum lorem';

  return theme('moon', $content); // use $content variable in moon.tpl.php template

  // Or you can use few 'variables' in hook_theme function
  // smth like this 'variables' => array('content1' => NULL, 'content2' => NULL)
  // and return page as theme('moon', var1, var2)
}


来源:https://stackoverflow.com/questions/5306559/drupal-7-how-to-assign-a-variable-to-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!