Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert code right after body tag using theme functions

I am trying to add a piece of code at the begining of every page in a Drupal site. Since I have more than one page template, I want to do this programatically... but am not succeeding.

I am still new and, though I get the gist of hooks, theme functions, and the such, I just can't figure the correct way to achieve this.

So far I've overriden the theme_preprocess_page(&$vars) to add the necessary css and js:

function mytheme_preprocess_page(&$vars) {
    if(condition) {
        drupal_add_js(drupal_get_path('module', 'mymodule').'/js/modal.js');
    }
}

How can I now add html code in every drupal page, preferably just after the opening bodytag or in any other starting section, via a function in the template.phpfile?

Thank you

like image 357
Naoise Golden Avatar asked Oct 27 '25 14:10

Naoise Golden


1 Answers

In your preprocess function, any variable set, will be available in your page.tpl.php file.

function mytheme_preprocess_page(&$vars) {
  if (condition) {
    $vars['foo'] = '<div id="bar">TEST</div>';
  }
}

then, in your page templates:

<body>
  <?php print !empty($foo) ? $foo : ''; ?>
...
like image 174
jhedstrom Avatar answered Oct 29 '25 15:10

jhedstrom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!