2
1

【Twig】テキストを置換

Posted at

文字列内の、あるキーワードを「削除」・「置換」したい時ってありますよね。

Replace

Twigにはreplaceというフィルターが標準で用意されています。

Sample

※ 公式より引用

{{ "I like %this% and %that%."|replace({'%this%': fruit, '%that%': "oranges"}) }}
{# if the "fruit" variable is set to "apples", #}
{# it outputs "I like apples and oranges" #}

{# using % as a delimiter is purely conventional and optional #}
{{ "I like this and --that--."|replace({'this': fruit, '--that--': "oranges"}) }}
{# outputs "I like apples and oranges" #}

ちょっとわかりづらいですかね。
大人気映画シリーズで使用例を紹介します。

使用例

このようなスニペットを用意してみました。

{% set title = movie %}
{% set clean_title = title|replace({'ジュラシック・パーク': ''}) %}
{{ clean_title or 'ジュラシック・パーク' }}

シリーズ1の場合

movieは「ジュラシック・パーク」ですね。
出力は以下の通り。

ジュラシック・パーク

シリーズ2の場合

movieは「ロスト・ワールド/ジュラシック・パーク」ですね。
出力は以下の通り。

ロスト・ワールド/

シリーズ3の場合

movieは「ジュラシックパークIII」ですね。
出力は以下の通り。

III

まとめ

僕のお気に入りはロストワールドです。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1