1``u``
2=====
3
4.. versionadded:: 2.12.1
5
6    The ``u`` filter was added in Twig 2.12.1.
7
8The ``u`` filter wraps a text in a Unicode object (a `Symfony UnicodeString
9instance <https://symfony.com/doc/current/components/string.html>`_) that
10exposes methods to "manipulate" the string.
11
12Let's see some common use cases.
13
14Wrapping a text to a given number of characters:
15
16.. code-block:: twig
17
18    {{ 'Symfony String + Twig = <3'|u.wordwrap(5) }}
19    Symfony
20    String
21    +
22    Twig
23    = <3
24
25Truncating a string:
26
27.. code-block:: twig
28
29    {{ 'Lorem ipsum'|u.truncate(8) }}
30    Lorem ip
31
32    {{ 'Lorem ipsum'|u.truncate(8, '...') }}
33    Lorem...
34
35The ``truncate`` method also accepts a third argument to preserve whole words:
36
37.. code-block:: twig
38
39    {{ 'Lorem ipsum dolor'|u.truncate(10, '...', false) }}
40    Lorem ipsum...
41
42Converting a string to *snake* case or *camelCase*:
43
44.. code-block:: twig
45
46    {{ 'SymfonyStringWithTwig'|u.snake }}
47    symfony_string_with_twig
48
49    {{ 'symfony_string with twig'|u.camel.title }}
50    SymfonyStringWithTwig
51
52You can also chain methods:
53
54.. code-block:: twig
55
56    {{ 'Symfony String + Twig = <3'|u.wordwrap(5).upper }}
57    SYMFONY
58    STRING
59    +
60    TWIG
61    = <3
62
63For large strings manipulation, use the ``apply`` tag:
64
65.. code-block:: twig
66
67    {% apply u.wordwrap(5) %}
68        Some large amount of text...
69    {% endapply %}
70
71.. note::
72
73    The ``u`` filter is part of the ``StringExtension`` which is not installed
74    by default. Install it first:
75
76    .. code-block:: bash
77
78        $ composer require twig/string-extra
79
80    Then, on Symfony projects, install the ``twig/extra-bundle``:
81
82    .. code-block:: bash
83
84        $ composer require twig/extra-bundle
85
86    Otherwise, add the extension explicitly on the Twig environment::
87
88        use Twig\Extra\String\StringExtension;
89
90        $twig = new \Twig\Environment(...);
91        $twig->addExtension(new StringExtension());
92