Twig-extensions in Symfony2

Twig comes with multiple filters that provide functions like round, slice, sort, etc. In case you need more filters Twig-extensions becomes handy because it implements all those filters that are not available by default:

  • Debug: Provides tags and filters to ease template debugging.
  • Text: wordwrap, truncate and nl2br for Strings.
  • i18n: Adds internationalization support via the gettext library.
  • Intl: localizeddate provides localization of DateTime objects.
  • Array: shuffle filter.

First you have to check if these Twig-extensions are already installed. Open composer.json and look for this:

    "require": {
        "twig/extensions": "1.0.*",

If you don’t have that, add it and run in the terminal:

composer update

Then you have to enable this extensions in config.yml:

        class: Twig_Extensions_Extension_Text
           - { name: twig.extension }

From now on you can use these extensions as usual in Twig templates:

    {{ name|truncate(10) }}


You might also like

Add Twig syntax highlight in Sublime Text 2
Select the "Preferences->Browse Packages..." menu to open the folder that contains Sublime Text 2 packages. Download...

Fix ‘A template that extends another one cannot have a body in …’ in Twig with Symfony2
This may be a confusing error at first but it's quite self explanatory. You can't have any HTML text...

Expose config.yml values globally for Twig templates in Symfony2 applications
Lets suppose you have created a bundle that has some specific configuration in the config.yml file (this...

Fix ‘ERROR: column “spclocation” does not exist’ in phpPgAdmin
I was going to create a new database with phpPgAdmin and it crashed with this error:ERROR: column...

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.