Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x. 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

uΒΆ

New in version 2.12.1: The u filter was added in Twig 2.12.1.

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:

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

Truncating a string:

1
2
3
4
5
{{ 'Lorem ipsum'|u.truncate(8) }}
Lorem ip

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

Converting a string to snake case or camelCase:

1
2
3
4
5
{{ 'SymfonyStringWithTwig'|u.snake }}
symfony_string_with_twig

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

You can also chain methods:

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

For large strings manipulation, use the apply tag:

1
2
3
{% 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:

1
$ composer req 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());
Website powered by Symfony and Twig, deployed on
The Twig logo is © 2010-2019 Symfony