Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fixed the template escaper guesser example
  • Loading branch information
fabpot committed Jul 13, 2012
1 parent e862905 commit 0d5a639
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions doc/recipes.rst
Expand Up @@ -335,25 +335,31 @@ you have some dynamic JavaScript files thanks to the ``autoescape`` tag:
But if you have many HTML and JS files, and if your template names follow some
conventions, you can instead determine the default escaping strategy to use
based on the template name. Let's say that your template names always ends
with ``.html`` for HTML files and ``.js`` for JavaScript ones, here is how you
can configure Twig::
with ``.html`` for HTML files, ``.js`` for JavaScript ones, and ``.css`` for
stylesheets, here is how you can configure Twig::

function twig_escaping_guesser($filename)
class TwigEscapingGuesser
{
// get the format
$format = substr($filename, strrpos($filename, '.') + 1);

switch ($format) {
'js':
return 'js';
default:
return 'html';
function guess($filename)
{
// get the format
$format = substr($filename, strrpos($filename, '.') + 1);

switch ($format) {
case 'js':
return 'js';
case 'css':
return 'css';
case 'html':
default:
return 'html';
}
}
}

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'autoescape' => 'twig_escaping_guesser',
'autoescape' => array(new TwigEscapingGuesser(), 'guess'),
));

This dynamic strategy does not incur any overhead at runtime as auto-escaping
Expand Down

0 comments on commit 0d5a639

Please sign in to comment.