u
¶
The u
filter wraps a text in a Unicode object (a Symfony UnicodeString instance) that
exposes methods to "manipulate" the string.
u フィルターは、文字列を「操作」するメソッドを公開する Unicode オブジェクト (Symfony UnicodeString インスタンス) でテキストをラップします。
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...
|
The truncate
method also accepts a third argument to preserve whole words:
truncate メソッドは、単語全体を保持するための 3 番目の引数も受け入れます。
1 2 |
{{ 'Lorem ipsum dolor'|u.truncate(10, '...', false) }}
Lorem ipsum...
|
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:
大きな文字列を操作するには、apply タグを使用します。
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:
u フィルターは、デフォルトではインストールされない StringExtension の一部です。最初にインストールします。
1 |
$ composer require twig/string-extra
|
Then, on Symfony projects, install the twig/extra-bundle
:
次に、Symfony プロジェクトで、twig/extra-bundle をインストールします。
1 |
$ composer require twig/extra-bundle
|
Otherwise, add the extension explicitly on the Twig environment:
それ以外の場合は、Twig 環境で拡張機能を明示的に追加します。
1 2 3 4 |
use Twig\Extra\String\StringExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new StringExtension());
|