Twig文字制限
Twig length
Twig slice
{{ myentity.text[:50] ~ (myentity.text|length > 50 ? '…') }}
補足:省略記号 ellipsis character ‘…’
スリードット ...
ではなく1つのキャラクターとして …
を表示
注)Linux:Ubuntuの場合(MAC,Windowsではキーが異なります)
- Ctrl + Shift + ‘u’ 押下
- キーリリース
- 続けて"2026"を入力,
- エンターキー押下
Twig dump
テンプレート内の変数確認
<pre>
{{ dump(item) }}
</pre>
Pimcore\Model\DataObject\Fieldcollection\Data\NewsText {#2378 ▼
#type: "NewsText"
#localizedfields: Pimcore\Model\DataObject\Localizedfield {#2384 ▶}
#index: 0
#fieldname: "content"
#object: null
#objectId: 1158
#dao: null
#_fulldump: false
#loadedLazyKeys: []
#o_dirtyFields: null
type: "NewsText"
localizedfields: Pimcore\Model\DataObject\Localizedfield {#2384 ▶}
index: 0
fieldname: "content"
object: null
objectId: 1158
_fulldump: false
loadedLazyKeys: []
o_dirtyFields: null
}
Twig striptags
htmlテキストファイルから <p>,<br>
等のタグを除外
EX) テキストソース頭から200文字を抽出後タグを削除。文字数が200文字を超えていたら '…'
による省略記号追加。
{% if news.content %}
{% for item in news.content.items %}
{% if item.type == "NewsText" %}
{{ item.text[:200] | striptags ~ (item.text|length > 200 ? '…') }}
{% endif %}
{% endfor %}
{% endif %}
'~'によるフィルタリングを施すと特殊文字(例:'
)がそのまま出力されてしまうため以下の記述に変更。
{% if news.content %}
{% for item in news.content.items %}
{% if item.type == "NewsText" %}
{{ item.text[:200] | striptags | raw }} .....
{% endif %}
{% endfor %}
{% endif %}
Twig Replace
上記のタグ削除に non-breaking space
の" "
への置換え追加
non-breaking spaceは、単位と数値の間の改行禁止のスペース
- § 10
- 10 km/h
- 10 PM
{% if news.content %}
{% for item in news.content.items %}
{% if item.type == "NewsText" %}
{{ item.text[:200] | striptags | replace({' ': " "}) ~ (item.text|length > 200 ? '…') }}
{% endif %}
{% endfor %}
{% endif %}
Twig Operators
条件設定
?:
: The ternary operator:
{{ foo ? 'yes' : 'no' }}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
Twig Logic
論理条件定義
and
: Returns true if the left and the right operands are both true.or
: Returns true if the left or the right operand is true.not
: Negates a statement.(expr)
: Groups an expression.
Twig Date
日付表示
Twig date_modify
{{ post.published_at|date_modify("+1 day")|date("m/d/Y") }}
Twig path
{{ path(route_name, route_parameters = [], relative = false) }}
name
type: string
parameters
(optional)
type: array
default: []
relative
(optional)
type: boolean
default: false
Returns the relative URL (without the scheme and host) for the given route. If relative
is enabled, it’ll create a path relative to the current path.
Other Operaters
-
|
: Applies a filter. -
~
: Converts all operands into strings and concatenates them. -
.
,[]
: Gets an attribute of a variable. -
?:
: The ternary operator: -
??
: The null-coalescing operator: