replace template with other when conditions are met
Solutions
You can alter the list of template suggestions in your preprocess
hook:
function drop_preprocess(&$variables) {
$variant = drop_get_variant_for_current_user($variables);
if ($variant) {
$suggestions = array();
foreach ($variables['theme_hook_suggestions'] as $suggestion) {
$suggestions[] = $suggestion
$suggestions[] = $suggestion . '--' . $variant;
}
$variables['theme_hook_suggestions'] = $suggestions;
}
}
This will add templates variants for all theme hook. So for instance, this allow you to override the node.tpl.php
and page.tpl.php
templates with node--special.tpl.php
and page--special.tpl.php
ones (when drop_get_variant_for_current_user()
returns 'special'
. If the template for a variant does not exists, it will simply be ignored.
Note that the order of suggestions is preserved. If you have three specialized node templates: node.tpl.php
, node--special.tpl.php
and node-article.tpl.php
(the default one, the 'special' variant and the template for article nodes), when rendering an article
node, the 'node-article.tpl.php' will be used since 'node_article'
will be after both 'node'
and 'node__special'
in $variables['theme_hook_suggestions']
.
Because it will run for all templates used on the page, the use a static cache in get_variant_for_current_user()
so the actual variant won't be computed again and again for the same request/template.
Update:
- The exact used template with be the last one in
$variables['theme_hook_suggestions']
for which a template file exits. For instance if$variables['theme_hook_suggestions'] == array('node', 'node--special', 'node-article', 'node-article--special')
, but only thenode.tpl.php
,node-article.tpl.php
andnode--special.tpl.php
files exist, thennode--special.tpl.php
will be used. - The
drop_get_variant_template()
function is the one where you put your variant selection logic (and that has to be written).