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

I have the following code in a template:
[% section ? ucfirst(section) _ ' - ' : '' %]
And what I mean is:
print ucfirst(section).' - 'if section;
But what I get is:
-
So my question is, what should I write to mean that, or what does Template think I mean by that. Either answer would be greatly helpful, as what I gleaned from the documentation has me under the impression that my statement is completely legal and should work.

Replies are listed 'Best First'.
Re: Template newbie question. Is it lack of understanding or lack of DWIM
by friedo (Prior) on Apr 16, 2007 at 18:51 UTC

    Template Toolkit doesn't support ucfirst as a method, but it does have a ucfirst filter. I don't think it supports the ternary operator, either. You could write it like this:

    [% IF section %][% section | ucfirst %] - [% END %]
      It does support the ternary operator, when I run that with section undef it produces nothing. Well I suppose I should finish reading aforementioned documentation instead of stopping after GET and SET. The filter solution feels somewhat less elegant though.
      You can make it a little less visually dense by changing it to something like the following (works in TT2 and CET):

      [% IF section ; section|ucfirst ; ' - ' ; END %]


      my @a=qw(random brilliant braindead); print $a[rand(@a)];
Re: Template newbie question. Is it lack of understanding or lack of DWIM
by Rhandom (Curate) on Apr 16, 2007 at 20:43 UTC
    TT3 will allow you to use a "|" wherever you use a "." now. It will also unify simple filters so that they will also work with the ".".

    It is possible in TT3 when it comes, or it is possible in CGI::Ex::Template now.

    use CGI::Ex::Template; my $t = CGI::Ex::Template->new; my $html = "Test: [% section|ucfirst _ '-' IF section %]\n"; $t->process(\$html, {section => "foo"}); $t->process(\$html, {section => ""}); __END__ prints: Test: Foo- Test:


    In most cases CGI::Ex::Template is a drop in replacement for Template.

    my @a=qw(random brilliant braindead); print $a[rand(@a)];