在Jekyll/Liquid中嵌套变量

Joo*_*stS 6 liquid jekyll

假设 - 根据我的理解,Liquid的工作方式是page.my_key可以将变量与名称page和密钥的PHP数组进行比较my_key:$page['my_key'].下面我们可以比较这同样的逻辑{{ page.my_key }}echo $page['my_key'].

我们可以比较这个前面的问题:

----
my_key: my_value
----
Run Code Online (Sandbox Code Playgroud)

这个PHP代码:

$page['my_key'] = "my_value";
Run Code Online (Sandbox Code Playgroud)

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

$page['my_key'] = "my_value";
$page['my_key2'] = "my_value2";
$key = "my_key";
echo $page[$key];
Run Code Online (Sandbox Code Playgroud)

我能想到的只有:

----
my_key: my_value
my_key2: my_value2
----
{% assign key = 'my_key' %}
{{ page.{{ key }} }}
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用......这样的事情可能吗?

Dav*_*uel 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"] }}
Run Code Online (Sandbox Code Playgroud)