【问题标题】:Can I modify a global Liquid variable from inside a Jekyll include?我可以从 Jekyll 包含中修改全局 Liquid 变量吗?
【发布时间】:2017-09-03 13:53:19
【问题描述】:

我想创建一个单独的 Jekyll 包含,它们都可以引用相同的公共变量。这是一个简化的场景。

我使用以下 Liquid 代码创建 _include/setter.html

{% globalString | append: include.add | append: "," %}

然后我使用以下 Liquid 代码创建_include/getter.html

we have {{ globalString }}

然后在我的页面中输入:

{% include setter.html add = "one" %}
{% include setter.html add = "two" %}
{% include getter.html %}

我希望看到类似we have one,two, 的结果。

当然globalString 不存在,所以这行不通。我似乎无法在 sitepage 中创建可以从包含中看到的新变量。现在我正在尴尬地使用capture 解决这个问题。有没有更好的方法将 Jekyll 中包含的数据 out 传递出去?

【问题讨论】:

    标签: global-variables jekyll liquid


    【解决方案1】:

    这可以在调用 includes 并将其作为参数传递之前设置全局变量:

    _includes/setter.html

    before: {{include.globalString}}<br>
    {% assign globalString = include.globalString | append: include.add | append: "," %}
    after: {{globalString}}<br>
    

    _includes/getter.htmlwe have {{ include.globalString }}

    然后:

    {% assign globalString = "" %}
    {% include setter.html add = "one" globalString=globalString%}
    {% include setter.html add = "two" globalString=globalString%}
    {% include getter.html globalString=globalString%}
    

    会输出:

    before:
    after: one,
    before: one,
    after: one,two,
    we have one,two, 
    

    更新

    它也可以在不传递“全局”变量作为参数的情况下工作,唯一的要求是在调用 includes 之前定义它:

    _includes/setter.html

    before: {{globalString}}<br>
    {% assign globalString = globalString | append: include.add | append: "," %}
    after: {{globalString}}<br>
    

    _includes/getter.htmlwe have {{ globalString }}

    {% assign globalString = "" %}
    {% include setter.html add = "one" %}
    {% include setter.html add = "two" %}
    {% include getter.html %}
    

    【讨论】:

    • 哇,这真是反直觉。在 setter 中使用 globalString 看起来像一个局部变量。我不知道这会影响二传手之外的价值。谢谢!超级有帮助!
    • @EFC 更新了答案,我发现没有参数也可以,代码变得更干净。
    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2016-12-28
    • 2012-10-28
    相关资源
    最近更新 更多