Twig nl2br
11 Jan 2011EDIT: nl2br is now available from Twig 1.5
I noticed there were a few people searching around for Twig nl2br… that is, using the nl2br tag within Twig.
Unfortunately there’s no default nl2br tag in Twig, however, there’s an extension that you can use that’ll give you: wordwrap, truncate and nl2br.
To do this:
- Get this file: Twig-extensions Text.php
- Read this: Twig Documentation – Using Extensions
- Put this:
$twig->addExtension(new Twig_Extension_Text());
BELOW where you’ve added your Twig Environment:
$loader = new Twig_Loader_Filesystem(current_theme); $twig = new Twig_Environment($loader); $twig->addExtension(new Twig_Extension_Text());
- Make sure the file you downloaded (Text.php) goes into the Extension directory. E.g. “twig/lib/Twig/Extension”
- Open up your template, find your variable and add |nl2br on the end of it:
{{ content|nl2br }}
There you have it! Other extensions are simply as easy too. I’ve yet to play with the i18n one, but it does sound fun!