2

I'm developing my first website with Drupal. So far it's going well but I have a few details I haven't figured out.

I want to load a random variable on each page load, in order to load a different color scheme each time.

My template is called 'fest' so I put this in my template.php:

$color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
$variables['color'] = $color;

If I put it in fest_preprocess_html the color var can be accessed in html.tpl.php but not in page.tpl.php. I want that variable available in node, page, html, everywhere. Putting this code in plain function fest_preprocess didn't work either. What am I doing wrong?

--EDIT Check @Berdir's answer, which led me to resolve this issue. This is the code I used after all:

function mytemplate_get_color() {
    static $color = NULL;


    if (!$color) {

        $colors = Array('red', 'blue', 'magenta', 'green');
        $rand_key = array_rand($colors, 1);
        $color = $colors[$rand_key];
    }

    return $color;
}

2 Answers 2

5

$variables are unique for each template. So if you implement hook_preprocess_html() and add something, then it is only available for html.tpl.php and nothing else.

I think the easiest way to achieve your goal is to create a new function in your template.php which sets the random color them the first time you access it and the returns the them on following calls. Then you can simply call that function from any template you want and it will return the same value on the same request. Such a function would look like this:

function yourtheme_get_color() {
  static $color = NULL;

  if (!$color) {
    // First call, define $colors here and then set $color.
    $color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
  }
  return $color;
}
1
  • Awesome! I updated the answer with the code I ended up using.
    – Ignacio
    Commented Oct 14, 2011 at 19:10
3

You need to put your code in fest_preprocess_page. The last part of the function name ('page' in this case) indicates the template name for which you're proprocessing variables.

function fest_preprocess_page(&$variables) {
  $color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
  $variables['color'] = $color;
}

Make sure to clear the cache after adding a preprocess function.

2
  • I'm under the impression I've already tried this, but I'll give it a go and see. Thanks!
    – Ignacio
    Commented Oct 14, 2011 at 15:18
  • Just to clarify, this would have worked ok if I just needed this in page.tpl, but I wanted to have this var available in page.tpl, html.tpl, etc. Thanks anyway :)
    – Ignacio
    Commented Oct 14, 2011 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.