将数组传递到包含来循环

时间:2019-03-14 23:18:40

标签: jekyll liquid

我有一个include,根据传入的内容,可以包含> 1个按钮。

当前,包含的内容如下:

{% if include.buttons %}
   {% for button in include.buttons %}
      <a class="{{ button.classes }}" href="{{ button.url }}">{{ button.title }}</a>
   {% endfor %}
{% endif %}

然后我要传递以下数据:

{% assign buttons = '[{ "title": "button 1", "url": "https://#", "classes": "btn btn-transparent" }, { "title": "button 2", "url": "https://#", "classes": "btn btn-primary" }]' %}
{% include header.html
   buttons=buttons
%}

我无法解决的问题是如何将数据正确传递到包含,以便我可以遍历它。

2 个答案:

答案 0 :(得分:1)

问题是将数据分配为数组。在液体中,您不能直接initialize arrays。一种解决方法是使用split

但是,使用jekyll可以通过data files提供数组。只需将您的按钮放在文件中,并使用以下命令说出_data\buttons.yml

postXX:
  - button1:
    - title: "button 1"
    - url: "https://#"
    - classes: "btn btn-transparent"
  - button2:
    - title: "button 2"
    - url: "https://#"
    - classes: "btn btn-primary"

现在,您可以将引用添加到帖子/页面的yaml标头中,例如:

---
your other yaml options....
buttons: postXX
---

最后,分配按钮并将其包含在代码中。

{% assign buttons = site.data.buttons[page.buttons] %}
{% include header.html
   buttons=buttons
%}

答案 1 :(得分:1)

使用Liquid,您无法创建带有文字表达式(如{% assign myArray = ["one","two","three"] %})的数组。

您只能:

  • 创建一个空的{% assign emptyArray = "" | split: "" %}
  • 从字符串{% assign myArray = "one two three" | split: " " %}
  • 中创建一个

然后您可以操纵数组:

因此,您的数组只能来自液体数组操作或配置,数据文件或页面前端问题中包含的某些数据。

相关问题