GitHub页面上Jekyll上Liquid变量的范围是多少 [英] What the the scope of Liquid variables on Jekyll on GitHub Pages
问题描述
我创建了一个简单的Jekyll页面(由GitHub Pages处理并托管),带有一个Liquid计数器变量,在其中我循环浏览一些数据并将其转储出去并计算具有给定属性的项目数.
I have created a simple Jekyll page (processed and hosted by GitHub Pages) with a Liquid counter variable where I loop through some data and dump it out and count the number of items with a given property.
例如:
Complete Before: {{ complete }}
{% for book in books %}
Title: {{book.Title}}
{% if book.Completed == "true" %}
{% increment completed %}
{% endif %}
{% endfor %}
Complete After: {{ complete }}
现在我在两个不同的页面上有相同的代码块,但是在两种情况下书中的数据都不同,但是变量completed
的值看起来像是在两个页面的处理过程中都保存了,导致一页看起来像
Now I have the same chunk of code on two different pages, but the data in books is different it both cases, but the value of the variable completed
looks like it's being saved across the processing of both pages which results in page one looking like
Complete Before:
Title: Foo
Title: Bar
Complete After: 2
第二页看起来像
Complete Before: 2
Title: Baz
Complete After: 3
如何使完成的变量在每个页面上都是唯一的,而无需将每个页面更改为使用不同的变量名.
How can I get the completed variable to be unique per page without needing to change each page to use a different variable name.
推荐答案
在这种情况下,我建议使用assign
并使用plus
过滤器递增变量. increment
的行为与预期的略有不同,它不会修改常见的Jekyll变量值:
I recommend to use assign
in this case and increment the variable with the plus
filter. increment
behaves a little different than one expects, it does not modify a common Jekyll variable value:
{% assign complete=0 %}
Complete Before: {{ complete }}
{% for book in books %}
Title: {{book.Title}}
{% if book.Completed == "true" %}
{% complete=complete | plus:'1' %}
{% endif %}
{% endfor %}
Complete After: {{ complete }}
更新
问题至少取决于它的范围,这不是我自然希望的,这是一个简单的示例来展示它:
Update
The problem relies in its scope, at least, that is not what I naturally expect, this is a simple example to show it:
{% for post in site.posts limit: 2%}
increment {{forloop.index}}
- before {{complete}}
- current increment: {% increment complete %}
- after {{complete}}
<hr>
{% endfor %}
New loop
{% for post in site.posts limit: 2%}
increment {{forloop.index}}
- before {{complete}}
- current increment: {% increment complete %}
- after {{complete}} EXPECTED: {{forloop.index}}
<hr>
{% endfor %}
输出:
increment 1
before
current increment: 0
after 1
increment 2
before 1
current increment: 1
after 2
New loop
increment 1
before 2
current increment: 2
after 3 EXPECTED: 1
increment 2
before 3
current increment: 3
after 4 EXPECTED: 2
这篇关于GitHub页面上Jekyll上Liquid变量的范围是多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!