4

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?

1 Answers1

7

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') %]
Kalyan02
  • 1,416
  • 11
  • 16
  • 1
    Thanks. The `{ user-name => "John" }` part is a typo and I fixed it in the question. And `[%user.item('user-name') %]` worked like a charm. Really appreciate that! –  Jun 19 '13 at 08:30
  • Unfortunately, a TT variable starting with an underscore is not expanded by TT. [% _lang %] remains empty, although the variable hash does contain { _lang => 'some value' } – Perlator Sep 18 '19 at 06:15