Last Updated: February 25, 2016
·
463
· mwetmore

D6: Swap Node Template based on Field Value

Sometimes we just want an easy way to swap a node template based upon a specified value of a field. In this case we have a field that defines some layouts, then we swap the node template based upon the field value.

Field Configuration:
fieldtemplatetype
Values:
layout1|Layout 1
layout2|Layout 2
layout3|Layout 3
layout4|Layout 4

Node Template File Configuration
node-layout1.tpl.php
node-layout2.tpl.php
node-layout3.tpl.php
node-layout4.tpl.php

Code for themepreprocess or themepreprocess_page

//field_template_type is used to allow the user to select a "Template"
$nodetemplate = 'node-'.$pnode->field_template_type[0]['value'];
//Setup the varialble that determines node template, format is node-<name>
//example file is node-retarticle1.tpl.php
$vars['template_files'][]=$nodetemplate;
//drupal_set_message($nodetemplate); <-If you ever need to view the details.

There are a few modules that do this, but they can be solved in just a few lines of code. This allow content editors to quickly define how the node should display when it is viewed.