Craft CMS ですべてのエントリーを取得したり、動的なキーの連想配列を作ったり、動的なキーで出力したりする Tips をご紹介します。
この記事は「Craft CMS Advent Calendar 2017」の 14 日目の記事です。今日は Craft CMS の基本的なお話になります。
Craft CMS でエントリーの情報を取得するとき、例えばセクションのハンドル名が blog
だったとすると、下記のように取得できます。
{% set blogs = craft.entries.section('blog') %}
例えば、Craft の blog セクションに 3,000 記事が登録されていたとすると、上記の書き方だと limit
の初期値である 100 件までしか取得できません。
もし、すべてのエントリーを取得したい場合は下記のようにして limit
に null
を渡せば OK です。
{% set blogs = craft.entries.section('blog').limit(null) %}
これを知らないと、ついつい .limit(99999)
とかやりそうですよね。
ついでに、すべてのセクションのすべてのエントリーを取得したい時は下記のよう書きます。
<ul>
{% for entry in craft.entries.limit(null) %}
<li>{{ entry.title }}</li>
{% endfor %}
</ul>
この場合は下記のように書きます。
{% for section in craft.sections.getAllSections() %}
<h2>{{ section.name }}</h2>
<ul>
{% for entry in craft.entries.section(section.handle).limit(null) %}
<li>{{ entry.title }}</li>
{% endfor %}
</ul>
{% endfor %}
この場合は下記のように書きます。 count()
を使えば簡単です。
<ul>
{% for section in craft.sections.getAllSections() %}
<li>{{ section.name }} = {{ craft.entries.section(section.handle).limit(null).count() }} エントリーあります。</li>
{% endfor %}
</ul>
ちなみに一度配列にセットしてあれば、 {{ 配列変数名 | length }}
でとれますね。
例えば entries
という連想配列があって、そのキーにセクションのハンドル名、値にそのセクションのすべてのエントリー、のような変数を作りたいときは下記のようにします。ついでにその連想配列の値を動的に取り出してみます(このテンプレートだけ見ると無駄が多いですが Tips として)。
{# キーを動的に連想配列をセットする #}
{% set entries = {} %}
{% set sections = {} %}
{% for section in craft.sections.getAllSections() %}
{% set entries = entries|merge({ (section.handle) : craft.entries.section(section.handle).limit(null)} ) %}
{% set sections = sections|merge({ (section.handle) : section.name }) %}
{% endfor %}
{# 動的にセットした連想配列を取り出す #}
{% for sectionHandle, sectionEntries in entries %}
{# 動的なキーで連想配列から取り出す #}
<h2>{{ attribute(sections, sectionHandle) }}({{ sectionHandle }})</h2>
<ul>
{% for entry in sectionEntries %}
<li>{{ entry.title }}</li>
{% endfor %}
</ul>
{% endfor %}
ポイントは、
| merge()
で動的にセットする()
で囲むattribute()
で取り出すといったところです。
以上です。