Ramón Devesa Ramón Devesa - 3 months ago 26
Twig Question

Limit String Twig

How can I limit a string length? I'm getting a description value from my database, but I want to only display a number of specific characters.


  • How can I do this in my twig template?

  • Is it better to do it within my controller?


Answer

Try with Truncate function:

First, you need to activated Text extension:

# app/config/config.yml
  services:
    twig.extension.text:
        class: Twig_Extensions_Extension_Text
        tags:
            - { name: twig.extension }

Then, you can call truncate() helper within your Twig template as follow:

{{ variable.description | truncate(100, true) }}