[Templates] Views in Template Toolkit
Andy Wardley
abw at wardley.org
Thu Jan 31 08:47:57 GMT 2008
Hi Noah,
> The "view" feature of TT, discussed in Chapter 3, left me excited but
> questioning why it's so limited. If different views can be provided for
> hashes, arrays, and scalars, why stop there?
...because the example in the book was just a brief introduction to views,
not an extensive discussion of them.
> The views should be
> declared based on class name, so an object of class "A::Beta" could have
> a different dynamic view from "A::Gamma" without any extra work on the
> programmer's part.
Yep, that's exactly what they do. From the documentation:
http://tt2.org/docs/manual/Views.html#section_Views_as_Data_Presenters
You can also provide templates to print objects of any other class. The
class name is mapped to a template name with all non-word character
sequences such as '::' converted to a single '_'.
[% VIEW foo %]
[% BLOCK Foo_Bar %]
a Foo::Bar object:
thingies: [% view.print(item.thingies) %]
doodahs: [% view.print(item.doodahs) %]
[% END %]
[% END %]
> Can anyone comment on the purpose and value of views, with respect to
> this reviewer's question?
The views reviewer should first review the views documentation. :-)
Views are an incredibly useful feature for a particular class of problem.
If you have a nested data structure of some kind (e.g. XML DOM) that you
want to transform using templates, then views are definitely worth a look.
They're officially experimental in TT2, largely because the particular
syntax I chose and a few of the internal details are likely to change in
the future (TT3). But that doesn't mean that they're not fully-formed
and functional.
A colleague on a recent project (using TT views to transform generic XML
to various different device-specific markup formats for mobile browsing)
described them thusly:
TT + VIEWS eq XSLT on crack
HTH
A
More information about the templates
mailing list