我试图在我的部分文件中使用一个变量,但它似乎不是从它的父模板继承的。
例如:
指数液体
{% assign foo = "bar" %}
{% section 'example' %}
Run Code Online (Sandbox Code Playgroud)
部分/示例.液体
<h1>{{ foo }}</h1>
{% schema %}
{
"name": "Example",
"settings": [
...
]
}
{% endschema %}
Run Code Online (Sandbox Code Playgroud)
它不会输出 的值{{ foo }},而我只是得到:<h1></h1>好像变量从未定义过一样。
我认为部分会像片段一样工作,其中父模板中定义的任何内容都在包含的片段中:
指数液体
{% assign foo = "bar" %}
{% include 'example' %}
Run Code Online (Sandbox Code Playgroud)
片段/example.liquid
<h1>{{ foo }}</h1>
Run Code Online (Sandbox Code Playgroud)
<h1>bar</h1>渲染时我会得到的地方。
谢谢!
如果这是预期的行为,我设法找到了解决方法,并认为我会发布我的不完美但可行的解决方案:
部分/示例.液体
<h1><!-- foo --></h1>
Run Code Online (Sandbox Code Playgroud)
您可以使用捕获,以字符串形式获取该部分的内容,并在捕获的标记上使用字符串过滤器:
指数液体
{% assign foo = "bar" %}
{% capture section %}{% section 'example' %}{% endcapture %}
{{ section | replace: '<!-- foo -->', foo }}
Run Code Online (Sandbox Code Playgroud)
您当然可以用您的变量替换任何字符串。但我发现 HTML 注释效果很好,因为如果您忘记运行替换或不需要运行 - 不会呈现任何内容。
如果你想做一些更复杂的事情,比如从部分中删除一些标记,你可以:
部分/示例.液体
<div>
<!-- REMOVE_TITLE? -->
<h1>{{ section.settings.title }}</h1>
<!-- REMOVE_TITLE? -->
<ul>
{% for block in section.blocks %}
<li>{{ block.settings.image | img_url: '300x' | img_tag }}</li>
{% endfor %}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
然后你可以做这样的事情:
{% capture section %}{% section 'example' %}{% endcapture %}
{% assign parts = section | split: '<!-- REMOVE_TITLE? -->' %}
{% for part in parts %}
{% assign mod = forloop.index | modulo: 2 %}
{% if mod > 0 %}{{ part }}{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |