global-variables - 我可以从 Jekyll 包含中修改全局 Liquid 变量吗?

标签 global-variables jekyll liquid

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

我使用以下 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 中?

最佳答案

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

_includes/setter.html:

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

_includes/getter.html:我们有 {{ 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.html:我们有 {{ globalString }}

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

关于global-variables - 我可以从 Jekyll 包含中修改全局 Liquid 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43290665/

相关文章:

c - 如何在大型 C 代码库中创建头文件?

html - Jekyll 中输出多个段落标签

html - 使用流畅的语法将每个单词的首字母大写?

C++静态变量初始化顺序

typescript - 检查 TypeScript 中是否存在内置类型?

c - 节点的全局变量

image - 为什么在 jekyll 网站上添加图像的 Markdown 语法不起作用?

ruby - 仅在存在时包含 Jekyll 模板

ruby-on-rails - 如何将所有 shopify 过滤器添加到标准液体中

jekyll - 如何按日期条件过滤列表?