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.


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>

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.



  1. Great Article
    Cloud Computing Projects

    Networking Projects

    Final Year Projects for CSE

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training


Post a Comment

Popular posts from this blog

Template Toolkit Debugging inside of Perl Dancer

BootstrapX clickover

Please don't create tests like this in Perl