【问题标题】:Passing parameters to inclusion in Liquid templates传递参数以包含在 Liquid 模板中
【发布时间】:2014-03-25 10:34:51
【问题描述】:

在我的 Jekyll 驱动的网站上,我有一个包含类似函数的内容,但我不知道如何正确传递它的参数。

当我使用{% include ... %}时,像这样传递参数..

{% include function.liquid foo="{{ baz.quux }}" %}

..它只是传递文字字符串{{ baz.quux }},这当然不是我想要的!我想传递baz.quux 的值。我该怎么做?

谢谢!

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    有两种方法可以实现这一点。我已经针对 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 }}

    在 Shopify 液体中

    截至 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

    【讨论】:

    • @Nick 我做了更多的研究并更新了我的答案。毕竟带参数的包含语法是可能的。
    • 关于这个stackoverflow.com/questions/22737362/…的任何想法::我有一个类似的问题:(
    • 第二种语法很棒。我在任何地方的文档中都看不到它,但它有效!
    • 除了纯文本或变量之外,有没有办法在include 中传递 HTML?我尝试使用捕获来传递 HTML 内容,但它被呈现为文本。
    • @RamPatra 可能最好写出您自己的问题,详细说明您正在尝试/尝试过的内容
    【解决方案2】:

    除了 David Hutchison 的之外,还有第三种解决方案:

    使用assign

    {% assign foo = baz.quux %}
    {% include function.liquid %}
    

    现在您可以在包含的文件中引用{{ foo }}

    【讨论】:

    • 这显然是首选方式。 6 年前提出问题时可能不可用。
    【解决方案3】:

    输入不带引号或括号的变量,如下所示:

    {% include footer.html param="value" variable-param=page.variable %}
    

    在你的情况下:

    {% include function.liquid foo=baz.quux %}
    

    它适用于我的网站。

    发件人:https://github.com/jekyll/jekyll/issues/3577#issue-61988857

    【讨论】:

      【解决方案4】:

      截至 2020 年 9 月 1 日,它确实是这样工作的:

      jekyll v4.1.1

      {% assign title = 'this is my tittle' %}
      {% include subscribeBtn.html title = title %}
      

      然后在模板中:

      <h3>{{ title }}</h3>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-04
        • 2014-01-16
        • 1970-01-01
        • 2021-11-24
        • 2018-05-26
        • 2014-02-01
        • 1970-01-01
        • 2020-10-17
        相关资源
        最近更新 更多