Perl Programming Page 3 - Looping, Security, and Templating Tools |
Using { and } to delimit code is fine for most uses of Text::Template--when you're generating form letters or emails, for instance. But what if you're generating text that makes heavy use of { and }-- HTML pages including JavaScript, for example, or TEX code for typesetting? One solution is to escape the braces that you don't want to be processed as Perl snippets with backslashes: if (browser == "Opera") \{ However, as one user pointed out, if you're generating TeX, which attaches meaning to backslashes and braces, you're entering a world of pain: \\textit\{ {$title} \} \\dotfill \\textbf\{ \\${$cost} \} A much nicer solution would be to specify alternate delimiters, and get rid of the backslash escaping: \textit{ [[[ $title ]]] } \dotfill \textbf{ [[[ $cost ]]] } Much clearer! To do this with Text::Template, use the DELIMITERS option on either the constructor or the fill_in method: print $template->fill_in(DELIMITERS => [ '[[[', ']]]' ]); This actually runs faster than the default because it doesn't do any special backslash processing, but needless to say, you have to ensure that your delimiters do not appear in the literal text of your template. Mark suggests a different trick if this isn't appropriate: use Perl's built-in quoting operators to escape the braces. If we have a program fragment { q{ if (browser == "Opera") { ... } } } Another problem is that your fingers fall off from typing: my $template = new Text::Template(...); all the time. The object-oriented style is perfect when you have a template that you need to fill in hundreds of times--a form letter, for instance--but not so great if you're just filling it in once. For these cases, Text::Template can export a subroutine, fill_in_file. This does the preparation and filling in all in one go: use Text::Template qw(fill_in_file); print fill_in_file("email.tmpl", PACKAGE => "Q", ...); Note that you do have to import this function specifically.
blog comments powered by Disqus |
|
|
|
|
|
|
|