Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Template Toolkit, Default and Zero

by marvell (Pilgrim)
on Aug 30, 2006 at 12:26 UTC ( [id://570368]=perlquestion: print w/replies, xml ) Need Help??

marvell has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed colleagues ...

I am using Template Toolkit and have an included component with a snippet of the form:

[% DEFAULT n = 1 %] [% x = f(n) %]

This works well unless I need to set n = 0:

[% INCLUDE snippet n=0 %]

At which point the default value is chosen.

My question, therefore, is ... is there a way of getting this to work without having to resort to this?

[% DEFAULT n = 1 %] [% IF z = 1; n = 0; END %] [% x = f(n) %]
[% INCLUDE snippet z=1 %]

Your time and efforts, as always, are appreciated.

--
Steve Marvell

Replies are listed 'Best First'.
Re: Template Toolkit, Default and Zero
by dtr (Scribe) on Aug 30, 2006 at 13:02 UTC

    Quoting from the Template::Manual::Directives perldoc page on the DEFAULT directive:-

    The DEFAULT directive is similar to SET but only updates variables that are currently undefined or have no "true" value (in the Perl sense).

    The following seems to work though:-

    [% UNLESS n.defined && n.length; n = 1; END %]

      Though not required, could this be turned into a MACRO?

      --
      Steve Marvell

      That worked nothing less that perfectly as a replacement for DEFAULT. Thanks.

      --
      Steve Marvell

Re: Template Toolkit, Default and Zero
by davidrw (Prior) on Aug 30, 2006 at 21:31 UTC
    did i over simplify, or does this work for you?
    [% x = f( z == 1 ? 0 : 1 ) %]
    Also note that besides the ternary operator you can also use the "reverse" condition syntax, just like perl... e.g. [$ SET n = 0 IF z = 1 %] is valid TT syntax.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://570368]
Approved by bart
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-26 00:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found