So, to answer my own question, for Template::Toolkit, this is a good way to do what I wanted in Template::Toolkit — though you're still free to suggest improvements :):
// BEGIN [% IF list -%] switch(x) { [% FOREACH item IN list -%] case [% item %]: // code for [% item %] [% UNLESS loop.last -%] break; [% END -%] [% END -%] } [% END -%] // END
Run together with the following code:
#! perl -w use Template; my $tt = Template->new(); foreach my $data ([undef => undef], [ empty => []], ['("foo", "bar", "baz")' => [qw(foo bar baz)]]) { print "// List is $data->[0]:\n"; $tt->process('tt2.tmpl', { list => $data->[1] }); print "\n\n"; }
// List is undef: // BEGIN // END // List is empty: // BEGIN switch(x) { } // END // List is ("foo", "bar", "baz"): // BEGIN switch(x) { case foo: // code for foo break; case bar: // code for bar break; case baz: // code for baz } // END
It's what I wanted, except for when the array is present but empty. How can you get the number of items in an array in TT2? I couldn't find that in the docs. I'd like to avoid having to add Perl code, setting a new value to the count of list items, both in the template (I think the template small language should stay perl-free), as in the script (as it might at some point be forgotten).
Oh, and I feel that I had to tweak it quite a bit just to get the proper amount of whitespace, adding the hyphens just at the right spots (those -%] thingies). Either I'm missing something, or Template::Toolkit could use a touchup.
I'd also like to indent the loop control directives, without that the added leading whitespace shows up in the output. Can it be done? It seems like I have to choose between stripping all whitespace (including newlines) just in front or right after the directives, or no stripping at all. Can't I strip leading whitespace just up to, but excluding, the newline?
In reply to Re^2: Templating suggestions for code generation
by bart
in thread Templating suggestions for code generation
by bart
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |