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

2018-08-20
1分で読了
更新: 2025-12-14

目次

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 %}

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

以上です。

この記事をシェア

この記事を書いた人

Roy Okuwaki

「かたつむりくんのWWW」を運営している Roy Okuwaki(tinybeans)です。bit part 合同会社 代表社員。2007年から、Movable Type や Craft CMS などの CMS、Web 開発、AI ツールの使い方について書いています。

プロフィールを見る →

関連記事