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