Twig の macro に渡す引数はハッシュ(連想配列)の方が良さそう

Twig のマクロを使う場合のちょっとした Tips です。

Craft CMS Logo

Twig の Macro 使ってますか?すごく便利ですよね。

でも今までは下記のように普通に複数の引数で変数を渡していました。

{% macro input(label, sectionHandle, nameList, type, classList, placeholder, hint, appendFieldContent) %}
...template...
{% endmacro %}

でもこうやるよりも、

{% macro input(options) %}
 {% set label = attribute(options, 'label') %}
 {% set sectionHandle = attribute(options, 'sectionHandle') %}
 {% set nameList = attribute(options, 'nameList') %}
 {% set type = attribute(options, 'type') %}
 {% set classList = attribute(options, 'classList') %}
 {% set placeholder = attribute(options, 'placeholder') %}
 {% set hint = attribute(options, 'hint') %}
 {% set appendContent = attribute(options, 'appendContent') %}
 ...template...
{% endmacro %}

とやった方が、後から変更しやすくていい場合が多いですね。

以上です。

Published 2018-08-20
Updated 2019-06-25