LoginSignup
8
12

More than 5 years have passed since last update.

JekyllのHTMLテンプレートで変数を使用する方法4種類

Last updated at Posted at 2015-06-11

_config.ymlで宣言した変数

site.(変数名)で呼び出すことができる。

_config.yml
hogeString: hogehoge
hoge:
  hage: hogehage
  fuge: hogefuge

index.html
...
<p>{{ site.hogeString }},{{ site.hoge.hage }},{{ site.hoge.fuge }}</p>
<!-- <p>hogehoge,hogehage,hogefuge</p> -->
...

YAML Front Matterで宣言した変数

page.(変数名)で呼び出すことができる。

_layouts/basic.html
...
<body id="{{ page.rootId }}" class="{{ page.rootClass }}">
<!-- <body id="index-page" class="index-page"> -->
  {{ content }}
</body>
index.html
---
layout: basic
rootClass: index-page
rootId: index-page
---
<p>hoge</p>
<!-- <body id="index-page" class="index-page"> -->
<!--   <p>hoge</p> -->
<!-- </body> -->

すべてのファイルで定義するのが面倒な場合、デフォルト値をFront Matter Defaultsにあらかじめ設定しておくことも可能な模様。

使い捨ての変数を宣言

宣言したファイルの中でしか参照できないと思う。

index.html
{% assign hogeVar = "hogehoge" %}
...
<ul class="{{ hogeVar }}">
  <li>{{ hogeVar }}</li>
</ul>
<!-- <ul class="hogehoge"> -->
<!--   <li>hogehoge</li> -->
<!-- </ul> -->

パーシャルをincludeする際にパラメータとして渡す

include先のファイル内にinclude.(変数名)を記述することでパラメータを親から子へ渡すことができる。ビューを再利用しやすくなるのでとても便利。

_includes/part.html
<input type="button" name="{{ include.name }}" value="{{ include.val }}" />
{% if include.name == "my-button" %}
  <small>This is mine!</small>
{% endif %}
index.html
...
<form>
  {% include part.html name="my-button" val="My Button" %}
  <!-- <input type="button name="my-button" value="My Button" /> -->
  <!-- <small>This is mine!</small> -->
  {% include part.html name="your-button" val="Your Button" %}
  <!-- <input type="button name="my-button" value="My Button" /> -->
</form>
...

使い分け

  • サイト全体で共通化したい文字列は、_config.yml内に記述
    • 例) title要素のサイト名部分
  • ページごとに異なる文字列が入る部分は、YAML Front Matter内に記述
    • 例) title要素の記事タイトル部分
  • 1ファイルの中で繰り返す文字列を単にまとめたい場合は、使い捨ての変数で記述

参考情報

8
12
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
8
12