u

The u filter wraps a text in a Unicode object (a Symfony UnicodeString instance) that exposes methods to “manipulate” the string.

Let’s see some common use cases.

Wrapping a text to a given number of characters:

{{ 'Symfony String + Twig = <3'|u.wordwrap(5) }}
Symfony
String
+
Twig
= <3

Truncating a string:

{{ 'Lorem ipsum'|u.truncate(8) }}
Lorem ip

{{ 'Lorem ipsum'|u.truncate(8, '...') }}
Lorem...

The truncate method also accepts a third argument to preserve whole words:

{{ 'Lorem ipsum dolor'|u.truncate(10, '...', false) }}
Lorem ipsum...

Converting a string to snake case or camelCase:

{{ 'SymfonyStringWithTwig'|u.snake }}
symfony_string_with_twig

{{ 'symfony_string with twig'|u.camel.title }}
SymfonyStringWithTwig

You can also chain methods:

{{ 'Symfony String + Twig = <3'|u.wordwrap(5).upper }}
SYMFONY
STRING
+
TWIG
= <3

For large strings manipulation, use the apply tag:

{% apply u.wordwrap(5) %}
    Some large amount of text...
{% endapply %}

Note

The u filter is part of the StringExtension which is not installed by default. Install it first:

$ composer require twig/string-extra

Then, use the twig/extra-bundle on Symfony projects or add the extension explicitly on the Twig environment:

use Twig\Extra\String\StringExtension;

$twig = new \Twig\Environment(...);
$twig->addExtension(new StringExtension());

© 2009–2018 by the Twig Team
Licensed under the three clause BSD license.
The Twig logo is © 2010–2020 Symfony
https://twig.symfony.com/doc/3.x/filters/u.html