HTML::String::TT - HTML string auto-escaping for Template Toolkit
my $tt = HTML::String::TT->new(\%normal_tt_args);
or, if you're using Catalyst::View::TT:
use HTML::String::TT; # needs to be loaded before TT to work __PACKAGE__->config( CLASS => 'HTML::String::TT', );
Then, in your template -
<h1> [% title %] <-- this will be automatically escaped </h1> <div id="main"> [% some_html | no_escape %] <-- this won't </div> [% html_var = '<foo>'; html_var %] <-- this won't anyway
(but note that the content key in wrappers shouldn't need this).
content
HTML::String::TT is a wrapper for Template Toolkit that installs the following overrides:
The directive generator is replaced with HTML::String::TT::Directive which ensures HTML::String::Overload is active for the template text.
The stash is forced to be Template::Stash since Template::Stash::XS gets utterly confused if you hand it an object.
A filter no_escape is added to mark outside data that you don't want to be escaped.
no_escape
The override happens to all of the plain strings in your template, so even things declared within directives such as
[% html_var = '<h1>' %]
will not be escaped, but any string coming from anywhere else will be. This can be a little bit annoying when you then pass it to things that don't respond well to overloaded objects, but is essential to HTML::String's policy of "always fail closed" - I'd rather it throws an exception than lets a value through unescaped, and if you care about your HTML not having XSS (cross site scripting) vulnerabilities then I hope you'll agree.
We mark a number of TT internals namespaces as "don't escape when called by these", since TT has a tendency to do things like
open FH, "< $name";
which really don't work if it gets converted to " $name while you aren't looking.
" $name
Additionally, since TT often calls ref to decide e.g. if something is a string or a glob, it's important that UNIVERSAL::ref is loaded before TT is. We check to see if the latter is loaded and the former not, and warn loudly that you're probably going to get weird errors.
ref
This warning is not joking. "Probably" is optimistic. Load this module first.
The no_escape filter marks the filtered input to not be escaped, so that you can provide HTML chunks from externally and still render them within the TT code.
See HTML::String for authors.
See HTML::String for the copyright and license.
To install HTML::String, copy and paste the appropriate command in to your terminal.
cpanm
cpanm HTML::String
CPAN shell
perl -MCPAN -e shell install HTML::String
For more information on module installation, please visit the detailed CPAN module installation guide.