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.