在Jekyll / Liquid中嵌套变量

时间:2016-07-13 12:07:24

标签: jekyll liquid

假设 - 据我所知,Liquid工作方式可以将变量page.my_key与名为page和密钥{{1}的PHP数组进行比较}:my_key。遵循相同的逻辑,我们可以将$page['my_key']{{ page.my_key }}进行比较。

我们可以比较这个前面的事情:

echo $page['my_key']

这个PHP代码:

----
my_key: my_value
----

问题 - 我想做类似的事情:

$page['my_key'] = "my_value";

我能想到的只有:

$page['my_key'] = "my_value";
$page['my_key2'] = "my_value2";
$key = "my_key";
echo $page[$key];

然而,这不起作用......这样的事情是否可能?

2 个答案:

答案 0 :(得分:2)

注意:数组和哈希是两种不同的动物。

只需在你的jekyll中创建一个 array-hash.md (请注意我在markdown中为简洁起见)。粘贴此代码。您将了解它们的不同以及如何访问它们的项目。

---
layout: default
title: array-hash
myArray:
 - item 1
 - item 2
 - one more
# or
myArray2: [ item 1, item 2, one more item ]
myHash:
 item1: toto
 "item 2": titi
 item 3: yoyo
---

{% comment %} +++ Shortcuts
  a = page.myArray
  h = page.MyHash 
  h2 = page.myArray2
{% endcomment %}

{% assign a = page.myArray %}
{% assign a2 = page.myArray2 %}
{% assign h = page.myHash %}

## Arrays

page.myArray : {{ a }}

page.myArray with inspect : {{ a | inspect }}

page.myArray with join : {{ a | join:", " }}

page.myArray2 : {{ a2 | inspect }}

### Looping the array
<ul>
{% for item in a %}
<li>{{ item | inspect }}</li>
{% endfor %}
</ul>

### Targeting a specific item in the array

{% comment %} arrays start at zero {% endcomment %}
second element in the array = {{ a[1] }}

Note that {% raw %}{{ a["1"] }}{% endraw %} will not work. You need to pass
an integer and not a string.

Test (not working) : { a["1"] }

## Hashes

page.myHash : {{ h }}

#### looping the hash

{% for item in h %}
 {{ item | inspect }}
{% endfor %}

You note that in the loop we get arrays that returns **key as item[0]**
and **value as item[1]**

The loop can then look like :

<ul>
{% for item in h %}
 <li>{{ item[0] }} : {{ item[1] }}</li>
{% endfor %}
</ul>

### Targeting a specific item in the hash

**Item1** due to the absence of space in the key name, can both me accessed
by dot notation (h.item1) or bracket notation (h["item1"]).

hash.item1 : {{ h.item1 }}

hash["item1"] : {{ h.["item1"] }}

Item 2 and 3, containing a space in their key string can only be accessed with
bracket notation :

hash.item 2 (not working) : {{ h.item 2 }}

hash["item 2"] : {{ h.["item 2"] }}

hash.item 3 (not working) : {{ h.item 3 }}

hash["item 3"] : {{ h.["item 3"] }}

答案 1 :(得分:0)

我想我找到了解决方案:

----
my_key: my_value
my_key2: my_value2
----
{% assign key = 'my_key' %}
{{ page[key] }}

找到它here