views:

180

answers:

3

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>
+3  A: 

This thread may help you

ccheneson
+9  A: 

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>
Adam Bellaire
Thank you. I did not know about `T:P:M`.
Sinan Ünür
Thank *you* for editing my answer into correctness. ;)
Adam Bellaire
You are welcome. Once you pointed me to `T:P:M`, the rest was straightforward.
Sinan Ünür
+4  A: 

If I have to do anything complex, I just use [%PERL%] sections and skip the Template Toolkit syntax.

Additionally, I figure out as much as I can in the controller and pass in a data structure of the values to use. I try to never select values or create new values in the template. Once you move logic into the template, you have to redefine it when you have another set of templates.

brian d foy
I agree with you on both counts, but in this case I had to fit something in to a very straightforward, existing web site.
Sinan Ünür
That's the sort of qualifier I put in the question. :)
brian d foy