Twig nl2br

11 Jan 2011

EDIT: 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! :-)

Tags: , ,

· · · ◊ ◊ ◊ · · ·

Twig Template Engine

30 Dec 2010

EDIT: nl2br() with Twig tutorial: twig-nl2br

A while back I started to learn django, and I absolutely loved it. However, I was so used to PHP for my web development, I naturally went back.

Then I found Twig! I’ve started using this in my latest project, and oh my! It’s an amazing little template engine. It’s definitely the best one I’ve ever used for PHP and the best thing is the fact it reminds me so much of how django does their templates. It’s very quick and easy to put in new themes, modify them… it’s a life-saver.

Some of the coolest things with Twig, is the fact you can do the whole nl2br (http://php.net/nl2br) stuff inside the template engine, for example:

{{ show_content|nl2br }}

How cool is that?! Another one, is transforming a raw timestamp to something much more readable. Ah, it’s a lifesaver.

I suggest you go visit the Twig site: http://www.twig-project.org/
And read the docs for template design: http://www.twig-project.org/doc/templates.html

P.S. I forgot to mention, the extensions are so easy to code for, and even easier to add to your project!

Tags: , , , ,

· · · ◊ ◊ ◊ · · ·