Search code examples
perltemplate-toolkit

Using Perl's Template.pm, how can I select a random element from an array and output it?


Suppose I have the following in my template:

[%- pages = [ 'one', 'two', 'three' ] -%]

<p>Go to page [%- ... -%]</p>

Assuming EVAL_PERL is not set (i.e., I cannot use a [%- PERL -%] block), what do I need to put inside the [%- ... -%] above so as to get the following output?

<p>Go to page "a randomly picked element of pages"</p>

Solution

  • There isn't any support for rand by default in Template, so you have to either import it via some other code (like Slash) or use Template::Plugin::Math, e.g.:

    [%- USE Math -%]
    
    [%- pages = [ 'one', 'two', 'three' ] -%]
    
    <p>Go to page [%- pages.${ Math.rand(pages.size) } -%]</p>
    

    Output:

    $ tpage test.html
    
    <p>Go to page three</p>