开发者

Adding a custom themable variable in theme_preprocess_page

开发者 https://www.devze.com 2023-02-12 07:15 出处:网络
I have read the docs over and over trying to wrap my head around this seemingly simple task. Basically, I have a template with a \'skip navigation\' div hard-coded in html.tpl.php that I do not want o

I have read the docs over and over trying to wrap my head around this seemingly simple task. Basically, I have a template with a 'skip navigation' div hard-coded in html.tpl.php that I do not want on front-page.

My idea was to set a $vars['skiplink'] variable in theme_preprocess_page. Since this variable contains a few lines of html markup, I was aiming for something as seen in garland theme:

function garland_preprocess_page(&$vars) {
  // Move secondary tabs into a separate variable.
  $vars['tabs2'] = array(
   '#theme' => 'menu_local_tasks',
   '#secondary' => $vars['tabs']['#secondary'],
  );

 <snip>

I would like to have the html in a themable function or even a template, but I cannot even get this snippet to work:

/**
 * Override or insert variables into the page template.
 */
function morin_preprocess_page(&$vars) {
  // add skiplink markup
  $vars['skiplink'] = 'hello world';
 }

This generates a notice:

Notice : Undefined variable: skiplink in include() (ligne 14 in /var/dev/morin/www/sites/all/themes/morin/templates/html.tpl.php).

Can anyone slap me with a clue? I would really like to understand how to do this with both methods, ( template & function ). I'm also wondering if this should be done in a module?

I realise there are probably 10 ways to skin this cat, so any insights on pros/cons of methods used are welcome.

Ok I figured out I was using the wrong preprocess function, setting $vars['skiplink'] in preprocess_html is开发者_运维百科 the way to go for top-level variables.I still have yet to figure out in a clear way how to associate this variable to a template file.


The preprocess hooks follow this pattern:

<theme name>_preprocess_<template name>

So if you want to modify the variables for "html.tpl.php" you want to use this hook:

<theme name>_preprocess_html(&$variables)


You are using preprocess_page but you are inserting the variable in the html.tpl.php.

You should either insert it in the page.tpl.php or rename your preprocess function, to add the variable to the html.tpl.php

And remember to clear cache if you didn't have the preprocess function defined already.

Update:
You seem to be missing a key point. Preprocess functions (along with the actual theme call) is how you make variables accessible in templates. Different preprocess functions are called for different templates, (..._page for page.tpl.php etc.)

Do you still have problems after using the correct preprocess function and clearing cache?

0

精彩评论

暂无评论...
验证码 换一张
取 消