Question

I'm using perl and Template::Toolkit to generate some texts. In the perl program, I defined a hash ref such as

my $user = { "user-name" => "John" };

and passed it to Template::Toolkit in order to generate John with the template file. In the template file I wrote

[% user-name %]

But unfortunately, user-name seemed to be recognized as a subtraction expression (user minus name) by Template::Toolkit.

To confirm my suspicions, I looked into the manual of Template::Toolkit to find the valid tokens to use in the variable name but found nothing.

So my questions are:

  1. Could you give the list of valid tokens for variable names of Template::Toolkit?

  2. Could I use some "escaping method" in the template file so that the variable name in perl program could remain user-name?

Was it helpful?

Solution

Generally, a valid perl variable is a valid template toolkit variable.

  • The variable should always start with a non numeric, non symbolic character [ A to Z and _ ]
  • Variable can only contain a to z, 0 to 9 and _ (underscore) characters.
  • Variable names cannot contain special symbols (it includes '-' symbol ).

Eg:

$user-name is not a valid perl variable. but $user_name is valid.

Here is what perl interpreter throws for your code

$ my $user = { user-name => "John" };                                                                                                      
Compile error: Bareword "user" not allowed while "strict subs" in use at (eval 294) line 5.

If you really want to use 'user-name' then you should define like this

$ my $user = { "user-name" => "John" };      
$ my $data = { user => $user };

And you should access it in your tt2 file like this:

[% user.item('user-name') %]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top