Saturday, August 25, 2012

Template Tooltip Tip #1

A bit of background

Template toolkit is a powerful and mature Perl based templating engine. It is designed to be output format agnostic and used (or able to be used) with most of the Perl based Web application frameworks like Dancer, Catalyst and CGI::Application.

TT Tip #1 - Simple html attribute macro

In this tip, i'll combine using a TT macro with HTML plugin to create a simple macro to add active class to html element.

code

TT code: (put in top of template or shared TT file pulled in with PROCESS or INCLUDE)
[% USE HTML %]
[% MACRO active GET HTML.attributes( 'class' => 'active' ) %]

Usage in a template:

<ul id="navBar"> 
  <li [% active IF page.name == 'home' %]>Home</li>
  <li [% active IF page.name == 'about' %]>about</li>
  <li [% active IF page.name == 'contact' %]>contact</li>
</ul>

In this case, when page.name matches then macro will drop in class="active". Simple but much more readable then a bunch of statements like:
[% IF page.name == 'home' %]class="active"[% END %]

I'm sure there are more elegant ways to create menu bar or breadcrumbs but this is intended to give you a feel of using a TT macro.

block with a process or include could be used but that ends up with template code like [% PROCESS active IF page.name == 'home' %] but i think the macro call is clearer with less directive line noise.

  __END__