LoginSignup
1
0

【CraftCMS】共通ファイルにパラメータを渡す

Last updated at Posted at 2019-05-16

とにかく共通化出来るものはしておきたい

htmlのヘッダとかフッタを共通化して使う時にファイルを分けて
twigでincludeすることはよくやる。
URL直叩きでファイルを開かれないようにするためには
ファイル名に_を付けておく。

index.html
{% include "_head.html" %} {# _head.htmlの中身が出力される #}

これでOK。

_head.htmlは例えばこんな感じ

_head.html
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
        <meta name="description" content="なんかのページはなんかします。">
        <title>なんかのページ</title>
    </head>

ところがこの場合、titleやdescriptionをページ別で切り替えることが出来ない。

とにかく楽したい

そこで思い出したのが「Smartyのタグに引数を付けてCSSを切り替える」こと
アレは確かタグ内でパラメータ渡してたような〜?

と思ってtwigのリファレンスを見てみたら…ありました。

Included templates have access to the variables of the active context.
If you are using the filesystem loader, the templates are looked for in the paths defined by it.
You can add additional variables by passing them after the with keyword:

sample.twig
{# template.html will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}

{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}

with付けて変数渡せば良さげなのでマネします。

index.html
{% 
set head = {
	"title":"test",
	"desc" : "description"
    }
{% include "_head.html" with head %} 
_head.html
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
        <meta name="description" content="{{head.desc}}">
        <title>{{head.title}}</title>
    </head>

headが未定義にならないよう

{% if head is not defined %}
    {% set head = { "title" : "DefaultTitle" , "desc" : "DefaultDescription" }
{% endif %}

もし「Descriptionは変えたいがtitleはデフォルトでいい!わざわざ書きとうない!」
という場合は呼び出し元で補完しといたらよいのかなー

{% if head.title is not defined %}
	{% set head = head|merge({"title":"DefaultTitle"}) %}
{% endif %}

配列を追加する場合はmergeを使うんだと

これでOK

1
0
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
1
0