0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Eleventy(11ty)でショートコードを含むファイルをループさせる

Last updated at Posted at 2023-10-18

11tyでショートコードを含むファイルをループさせようとするとエラーが発生していたのですが、v1.0.0で解消できたのでご紹介します。

エラーが生じる例

Eleventyで画像を扱う時はeleventy-imgでwebpとavif形式にも変換しています。
例えば、下記のようにショートコードを設定しています。

ショートコード
{% image "./src/media/images/hoge/hoge.jpg", "width", "height", "alt" %}
出力されるHTML
<picture>
  <source type="image/avif" srcset="/media/images/hoge/hoge.avif">
  <source type="image/webp" srcset="/media/images/hoge/hoge.webp">
  <source type="image/jpeg" srcset="/media/images/hoge/hoge.jpeg">
  <img src="/media/images/hoge/hoge.jpeg" width="width" height="height" alt="alt">
</picture>

記事一覧ページを作成するとして、各ブロックに上記のショートコードを設定しているファイルをincludeしてループさせたいとします。
その際、ショートコードに設定する値は配列のデータから設定するとします。

archive.njk
{%- for article in articlesData %}
  {% include 'parts/archive_card.njk' %}
{%- endfor %}
parts/archive_card.njk
<div>
  <h2>{{ article['articleTitle'] }}</h2>
  <p>{{ article['articleDesc'] }}</p>
  {% image article['imgSrc'], article['imgWidth'], article['imgHeight'], article['imgAlt'] %}
</div>

上記で実行しようとすると、エラーが発生してコンパイルされません。
ショートコードはやめて、直接imgタグで画像を読み込む方法に切り替えていました。

v1.0.0 で追加された {% setAsync %} で解消

22年10月リリースのv1.0.0で追加された{% setAsync %}で解消することができました。

archive.njk
{%- for article in articlesData %}
  {% setAsync 'articleImg' %}
    {% image article['imgSrc'], article['imgWidth'], article['imgHeight'], article['imgAlt'] %}
  {% endsetAsync %}

  {% include 'parts/archive_card.njk' %}
{%- endfor %}
parts/archive_card.njk
<div>
  <h2>{{ article['articleTitle'] }}</h2>
  <p>{{ article['articleDesc'] }}</p>
  {{ articleImg }}
</div>

上記のように{% setAsync %}でショートコードを登録し、
includeするファイルで{% setAsync %}で設定した変数を呼び出すことでエラーを解消することができました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?