【发布时间】:2014-03-25 10:34:51
【问题描述】:
在我的 Jekyll 驱动的网站上,我有一个包含类似函数的内容,但我不知道如何正确传递它的参数。
当我使用{% include ... %}时,像这样传递参数..
{% include function.liquid foo="{{ baz.quux }}" %}
..它只是传递文字字符串{{ baz.quux }},这当然不是我想要的!我想传递baz.quux 的值。我该怎么做?
谢谢!
【问题讨论】:
在我的 Jekyll 驱动的网站上,我有一个包含类似函数的内容,但我不知道如何正确传递它的参数。
当我使用{% include ... %}时,像这样传递参数..
{% include function.liquid foo="{{ baz.quux }}" %}
..它只是传递文字字符串{{ baz.quux }},这当然不是我想要的!我想传递baz.quux 的值。我该怎么做?
谢谢!
【问题讨论】:
有两种方法可以实现这一点。我已经针对 Jekyll 的 github-pages 版本测试了这两种方法。
假设您在包含的代码中引用{{ foo }},您需要在调用包含之前为 foo 分配一个值。
如:
{% capture foo %}{{ baz.quux }}{% endcapture %}
{% include function.liquid %}
这允许您控制变量的范围,就像您想要的那样。在the templates documentation 中有一些关于如何设置的细节。
在您将使用的模板中,您的语法几乎是正确的:
{% include function.liquid foo=baz.quux %}
缺少的部分是在include文件的代码中需要对变量进行不同的引用,需要使用{{ include.foo }}
截至 2021 年,您可以执行以下操作:
{% include 'snippet-file' with bar, foo: baz, foo2: baz2 %}
在 sn-p 文件中,使用 {{ snippet-file }} 检索 bar 和使用 {{ foo }} 检索 baz。
对于 Liquid 语句,只需使用不带{{ }} 的变量名,例如:
{% if snippet-file==0 and foo2==':)' %}
请注意,它不会像上一节中显示的那样像 include.foo2 那样工作。
另请注意,include 已弃用,对于新开发,您应该以类似的方式使用 render。
【讨论】:
include 中传递 HTML?我尝试使用捕获来传递 HTML 内容,但它被呈现为文本。
除了 David Hutchison 的之外,还有第三种解决方案:
{% assign foo = baz.quux %}
{% include function.liquid %}
现在您可以在包含的文件中引用{{ foo }}。
【讨论】:
输入不带引号或括号的变量,如下所示:
{% include footer.html param="value" variable-param=page.variable %}
在你的情况下:
{% include function.liquid foo=baz.quux %}
它适用于我的网站。
发件人:https://github.com/jekyll/jekyll/issues/3577#issue-61988857
【讨论】:
截至 2020 年 9 月 1 日,它确实是这样工作的:
jekyll v4.1.1
{% assign title = 'this is my tittle' %}
{% include subscribeBtn.html title = title %}
然后在模板中:
<h3>{{ title }}</h3>
【讨论】: