jekyll 中的 Liquid 变量包含参数

问题描述 投票:0回答:2

我在

_includes
中有一个 jekyll 部分,它在其内容周围包裹着一个彩色的 div。部分(
callout.html
)看起来像这样:

<div markdown="1" class="callout">
    {{ include.content }}
</div>

我这样称呼它:


test.md

但是,这会导致 Liquid 抛出错误:

{% include callout.html content="Content to be filled with a URL: {{ site.baseurl }}/img/test.png" %}

我相信这个问题是由于我在 
Liquid Exception: Invalid syntax for include tag: ... " Valid syntax: {% include file.ext param='value' param2='value' %} in bundler: failed to load command: jekyll (/usr/local/lib/ruby/gems/2.6.0/bin/jekyll)

参数中包含了

{{ site.baseurl }}
造成的。

我怎样才能绕过这个限制?

html ruby jekyll liquid
2个回答
2
投票
https://jekyllrb.com/docs/includes/#passing-parameter-variables-to-includes

我在发布后不久就在 Jekyll 文档中找到了答案。

content

参数的值应在使用

content
传递给包含之前单独存储为变量。对于上面的例子:

capture



0
投票

使用

{% capture callout_content %} Content to be filled with a URL: {{ site.baseurl }}/img/test.png {% endcapture %} {% include callout.html content=callout_content %}

,可以传递参数,例如要包含的文件名和要包含的任何变量(在本例中为“内容”)作为参考:

{% include %}
关于你列出的例子,我会如何做:

{% include {{ file }} content='...' url='...' %}

当然在 callout.html 包含文件中:

{% assign image_url = site.baseurl | append: '/img/test.png' | strip %} {% include callout.html text='Content to be filled with a URL:' url=image_url %}

不确定它是否更干净/更好/更快,但我不喜欢在内容中混合/匹配文本和变量,这只是感觉很恶心。

增加更多的复杂性和进一步的定制...可能有点偏离主题,但它确实展示了包含的真正力量。

我确实想强调,通过包含和传递变量作为页面或前言或模板上人类输入文本的引用,您应该始终考虑使文本“安全”:

<div class="callout"> {{ include.text }} {{ include.url }} </div>

| strip
等都是你的朋友:
| uri_escape

在这种情况下,我特别没有在文本变量中包含 
{% if page.callout.enabled == true %} {% assign file = 'callout.html' %} {% assign text = 'Content to be filled with a URL: ' %} {% assign image_url = site.baseurl | append: page.image | uri_escape | strip %} {% include {{ file }} text=text image_url=image_url %} {% elsif page.comments.enabled == true %} {% assign file = 'components/comments/disqus.html' %} {% include {{ file }} %} {% endif %}

,因为它会删除尾随空格。更喜欢在模板包含的文件中保留空格,而不是以这种方式传递的变量 - 它们之后不可能进行比较和/或处理,但是当将它们分离成单独的变量然后传递到包含中时,您可以。

    

© www.soinside.com 2019 - 2024. All rights reserved.