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 body
tag or in any other starting section, via a function in the template.php
file?
Thank you
Had a look at https://www.drupal.org/project/google_tag. This is how they did it:
You can add it to the footer with an option passed into the drupal_add_js function.
This will end up printing just before the closing body tag via the
$page_bottom
variable in the templatehtml.tpl.php
.Another way to do it is to use the native drupal methods
drupal_add_js
anddrupal_get_js
.// first, add your JS with a custom "scope" (before process phase)
// ugly way : add the
drupal_get_js
directly intohtml.tpl.php
(but for testing, it's useful):// A cleaner way : use an intermediate variable, in a process method // Exactly like
template_process_html
, intheme.inc
Enjoy :)
In your preprocess function, any variable set, will be available in your page.tpl.php file.
then, in your page templates:
This should keep you from having to modify any code in your templates:
My approach finally was overriding the first rendered block in the page, in my case the Language Switcher. Since I already was overriding it to customize it, it wasn't too much of a big deal, but it is anyway an ugly way to achieve that.
Since the Language Switcher is rendered in every page, it works. The day the language switcher stops being displayed for whatever reason, this solution will FAIL.