File: u.rst

package info (click to toggle)
php-twig 2.14.3-1%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,240 kB
  • sloc: php: 18,830; makefile: 215; sh: 42; python: 33
file content (86 lines) | stat: -rw-r--r-- 1,837 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
``u``
=====

.. versionadded:: 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 <https://symfony.com/doc/current/components/string.html>`_) that
exposes methods to "manipulate" the string.

Let's see some common use cases.

Wrapping a text to a given number of characters:

.. code-block:: twig

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

Truncating a string:

.. code-block:: twig

    {{ '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:

.. code-block:: twig

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

Converting a string to *snake* case or *camelCase*:

.. code-block:: twig

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

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

You can also chain methods:

.. code-block:: twig

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

For large strings manipulation, use the ``apply`` tag:

.. code-block:: twig

    {% 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:

    .. code-block:: bash

        $ 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());