Shopify部分中的可变范围

时间:2018-06-14 10:03:01

标签: shopify-template

我试图在我的部分文件中使用变量,但它似乎不会从它的父模板继承。

例如:

index.liquid

{% assign foo = "bar" %}
{% section 'example' %}

段/ example.liquid

<h1>{{ foo }}</h1>

{% schema %}
{
    "name": "Example",
    "settings": [
       ...
    ]
}
{% endschema %}

它不会输出{{ foo }}的值,而只是得到:<h1></h1>,好像变量从未定义过。

我认为部分可以像片段一样工作,其中父模板中定义的任何内容都在包含的片段的范围内:

index.liquid

{% assign foo = "bar" %}
{% include 'example' %}

段/ example.liquid

<h1>{{ foo }}</h1>

渲染时我会得到<h1>bar</h1>

  • 这是一个错误,还是预期的行为?
  • 有没有办法可以包含一个部分并使用某种形式的外部范围变量?

谢谢!

2 个答案:

答案 0 :(得分:3)

如果这是预期的行为,我设法找到一种解决方法,并认为我会发布不完美但可行的解决方案:

<强>段/ example.liquid

<h1><!-- foo --></h1>

您可以使用捕获,将该部分的内容作为字符串获取,并在捕获的标记上使用字符串过滤器:

<强> index.liquid

{% assign foo = "bar" %}
{% capture section %}{% section 'example' %}{% endcapture %}
{{ section | replace: '<!-- foo -->', foo }}

你当然可以用你的变量替换任何字符串。但是我发现HTML工作得很好,因为如果你忘记运行替换,或者不需要 - 什么都不会被渲染。

如果你想做一些更复杂的事情,比如你可以从以下部分删除一些标记:

<强>段/ example.liquid

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

然后你可以这样做:

{% 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 %}

答案 1 :(得分:1)

我将在一个代码段中分配所有变量,并在需要使用变量的任何范围内将其包含在相同的代码段中。...

那是一种相当干燥的方法。

config / settings_schema.json中定义的任何内容都具有全局范围,但最终用户可以在主题设置中为其赋予新值。

相关问题