Search code examples
perltemplate-toolkit

How can I output perl Template Toolkit examples in Template ToolKit


I'm making some documentation for Template Toolkit via Template Toolkit files. The goal is to show the code that I'm using along with the outputs of the code. Right now, I'm doing this by making a copy of the code and replacing all the "%" characters with "%" strings.

So, I'd have something like this:

The Template Toolkit code:

    [% FOREACH name IN nameArray %][% name %][% IF !loop.last %], [% END %][% END %]

Produces the output:

    [% FOREACH name IN nameArray %][% name %][% IF !loop.last %], [% END %][% EN D%]

Which will output something like:

The Template Toolkit code:

    [% FOREACH name IN nameArray %][% name %][% IF !loop.last %], [% END %][% END %]

Produces the output:

    George, Jane, Judy, Elroy

My question is if there is a alternate/better way to do this? Ideally one where I don't have to effectively duplicate the code each time.


Solution

  • I found a very simple solution:

    1. Move the example code to its own file.

    2. In the main template, use both the INSERT and INCLUDE Template Toolkit directives to call the example code file.

    The INSERT directive outputs the contents of the file directly (i.e. with no processing). The INCLUDE directive processes the file in the normal Template Toolkit way before outputting it.

    For example, take the following three files:


    File: process_template.pl

    #!/usr/bin/perl 
    
    use strict;
    use warnings;
    use Template;
    
    my %data = (
        nameArray => [ 'George', 'Jane', 'Judy', 'Elroy' ]
    );
    
    my $tt_obj = Template->new();
    $tt_obj->process('main.tmpl', \%data) || die $tt_obj->error();
    

    File: main.tmpl

    The Template Toolkit code:
    
    [% INSERT "code_example.tmpl" %]
    
    Produces the output:
    
    [% INCLUDE "code_example.tmpl" %]
    

    File: code_example.tmpl

        [% FOREACH name IN nameArray %][%name%][% IF !loop.last %], [%END%][%END%]
    

    When "process_template.pl" is run, it will produce the expected output. As an added benefit, placing the sample snippets of code in their own files makes them easier to edit/manage/maintain.