Where to add custom theme function that generates HTML? I am making a theme for Drupal 7 that includes an HTML5/CSS3 animation in the header. The animation works fine, but I want to generate the HTML for it dynamically so there is an element of randomness.

At the moment I am doing this via a pair of simple for loops in page.tpl.php but I am aware this isn't really the best place to put the code. I have spent a little while searching and most answers seem to deal with modifying variables or code that Drupal puts out, whereas this is generating some completely new HTML.

What is the "Drupal way" to handle this? Just add a custom function to template.php that I call (themename_mycustomfunction) or do it in the preprocessor function (themename_preprocess_page) to add the generated HTML as a variable?
Thanks

EDIT: This is the code I've currently got located at the top of my page.tpl.php. Nothing fancy, just generates some divs with the classes that the CSS3 animation will use. Where is the best place to put it though?

&lt;div id="anim"&gt;
    &lt;?php
    for ($i = 1; $i &lt;= 10; $i++) {
        ?&gt;
        &lt;div class="block o&lt;?php print rand(1,3); ?&gt; w&lt;?php print rand(1,6); ?&gt; x&lt;?php print rand(1,9); ?&gt; start"&gt;&lt;/div&gt;
        &lt;?php
    }
    ?&gt;
    &lt;?php
    for ($i = 1; $i &lt;= 20; $i++) {
        ?&gt;
        &lt;div class="block o&lt;?php print rand(1,3); ?&gt; w&lt;?php print rand(1,6); ?&gt; x&lt;?php print rand(1,9); ?&gt;"&gt;&lt;/div&gt;
        &lt;?php
    }
    ?&gt;
&lt;/div&gt;
Your nearly there...

If your going to do this on the theme layer then create the custom function and call it in a process function assigning to a variable that can be passed to the template.

Thats typically the "Drupal way".

template.php

function THEME_customFunction() {
   // blah blah...
}


template.php

function THEME_preprocess_page(&amp;$vars) {
   // blah blah...

   $vars['animation'] = THEME_customFunction();

}


page.tpl.php

&lt;?php if ($animation): ?&gt;
&lt;?php print $animation; ?&gt;
&lt;?php endif; ?&gt;