【问题标题】:jekyll: Is it possible to use a page.variable, as an operator inside a conditional if statement?jekyll:是否可以在条件 if 语句中使用 page.variable 作为运算符?
【发布时间】:2018-02-23 00:49:23
【问题描述】:

路径中的 JSON 文件:_data/integers.json,如下所示:

{
    "100": [
        {
            "value": "true"
        }
    ]
}

在 Jekyll 页面中:

---

integers:
- 100
- 200

---

我正在尝试做的事情:

{% assign json = site.data.integers %}
{% for integer in page.integers %} // loop
 {% if json.{{ integer }}[0].value == "true" %} ... {% endif %}
{% endfor %}

例如在条件语句中使用{{ integer }}(又名page.integer[0])作为运算符。

有方法吗? ... 找朋友。

【问题讨论】:

    标签: json jekyll liquid


    【解决方案1】:

    如果我们保持您的 json 和 page.integers 不变:

    {% assign json = site.data.integers %}
    {{ json | inspect }}
    {% for integer in page.integers %}
      {% comment %} Here we cast our integer to a string, 
                    as json keys are strings
                    (100 | append:"" => "100")
      {% endcomment %}
      {% assign intAsStr = integer | append:"" %}
    
      {% comment %} as a possible json[intAsStr] returns an array,
                    we retrieve the first and only element in it 
      {% endcomment %}
      {% assign data = json[intAsStr].first %}
    
      {% if data["value"] == "true" %}
        <h1>We have a match on {{ intAsStr }}</h1>
      {% endif %}
    {% endfor %}
    

    我们可以通过一些重构来简化一点

    数据/整数.json

    {
        "100": { "value": true }
    }
    

    jekyll 页面

    ---
    integers:
      - "100"
      - "200"
    ---
    
    {% assign json = site.data.integers %}
    {{ json | inspect }}
    {% for integer in page.integers %}
      {% assign data = json[integer] %}
      {% if data["value"] == true %}
         <h1>We have a match on {{ integer }}</h1>
      {% endif %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2018-09-26
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多