views:

77

answers:

1

I have to display different medical forms according to which state the user is in. There is also a default form that many of the states share. These medical forms are all written in Template Toolkit and they are included in larger templates. The state is available as a variable in a normalized form.

I need to select the state-specific template, if it exists, otherwise fall back to the default. How would I best go about doing this?

INCLUDE_PATH is already being used to control switching between site styles.

+5  A: 

Something like this should do the job:

main.tt:

This is a main template [% GET state %]
[% SET iname = state _ ".tt" %]
[% TRY %]
[% INCLUDE "$iname" %]
[% CATCH %]
[% INCLUDE default.tt %]
[% END %]
End of main template

default.tt:

This is default template

s1.tt:

This is template for state s1.

t.pl:

#! /usr/bin/perl
use 5.006;
use strict;
use warnings;

use Template;
my $tt = Template->new();
$tt->process("main.tt", { state => "s1" })
  || die $tt->error, "\n";
print "---------\n";
$tt->process("main.tt", { state => "unknown" })
  || die $tt->error, "\n";

When running t.pl:

This is a main template s1
This is template for state s1.
End of main template
---------
This is a main template unknown
This is default template
End of main template
Grrrr
That looks like it'll work, thanks! And I can abstract it away into a utility template so I can do something like `[% INCLUDE "util/bystate" template = "some_form.tt2" ]`
Schwern