在 Jekyll/Liquid 中嵌套变量

Nesting variables in Jekyll/Liquid

假设 - 据我了解,Liquid 的工作方式是变量 page.my_key 可以与名称为 [= 的 PHP 数组进行比较16=] 和密钥 my_key$page['my_key']。按照同样的逻辑,我们可以比较 {{ page.my_key }}echo $page['my_key']

我们可以比较前面的内容:

----
my_key: my_value
----

此PHP代码:

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

问题 - 我想做这样的事情:

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

我能想到的就是:

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

但是,这行不通...但是这样的事情可能吗?

我想我找到了解决方案:

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

找到了here

注意:数组和散列是两种不同的动物。

只需在你的 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"] }}