Shopify - 将变量传递到 if 语句中?
Shopify - Pass a variable into a if statement?
我正在尝试根据客户拥有的标签在 customer/account.liquid 页面上显示产品列表。
在文件的最顶部,我捕获了名为 topic
的变量
{% capture topic %}
{% for tag in customer.tags %}
{{ tag }}
{% endfor %}
{% endcapture %}
几行之后我想在 if 语句中重新使用我的变量以仅显示具有完全相同标签的产品。
我现在已经这样做了,但我无法让它工作。
{% for product in collections.all.products %}
{% for tag in product.tags %}
{% if tag contains [topic] %}
<a href="{{ product.url }}">
{% for image in product.images %}
<img src="{{ image.src | product_img_url: 'medium' }}">
{% endfor %}
<span>{{ product.title }}</span>
<span>{{ product.type }}</span>
</a>
{% endif %}
{% endfor %}
{% endfor %}
你能帮我找出我的错误吗?
非常感谢!
朱利安
您的方法几乎没有问题。客户标签是一个数组,主题的值将是 for 循环之后的所有标签作为字符串。因此,您的比较因单个标签而失败。以下代码应该适合您。
{% for product in collections.all.products %}
{% assign displayProduct = false %}
{% for tag in product.tags %}
{% if customer.tags contains tag %}
{% assign displayProduct = true%}
{% endif %}
{% endfor %}
{% if displayProduct == true %}
<a href="{{ product.url }}">
{% for image in product.images %}
<img src="{{ image.src | product_img_url: 'medium' }}">
{% endfor %}
<span>{{ product.title }}</span>
<span>{{ product.type }}</span>
</a>
{% endif %}
{% endfor %}
在上面的代码中,您遍历每个产品标签并查看客户标签数组是否包含相同的值。如果是这样,请将 displayProduct 设置为 true。使用标志变量而不是仅仅使用 if 条件来显示产品的原因是,如果用户和产品有多个相同的标签,这可以防止多次呈现相同的产品。
您可以通过仅在客户有一些标签时迭代产品来进一步改进这一点。
我正在尝试根据客户拥有的标签在 customer/account.liquid 页面上显示产品列表。
在文件的最顶部,我捕获了名为 topic
的变量{% capture topic %}
{% for tag in customer.tags %}
{{ tag }}
{% endfor %}
{% endcapture %}
几行之后我想在 if 语句中重新使用我的变量以仅显示具有完全相同标签的产品。
我现在已经这样做了,但我无法让它工作。
{% for product in collections.all.products %}
{% for tag in product.tags %}
{% if tag contains [topic] %}
<a href="{{ product.url }}">
{% for image in product.images %}
<img src="{{ image.src | product_img_url: 'medium' }}">
{% endfor %}
<span>{{ product.title }}</span>
<span>{{ product.type }}</span>
</a>
{% endif %}
{% endfor %}
{% endfor %}
你能帮我找出我的错误吗?
非常感谢!
朱利安
您的方法几乎没有问题。客户标签是一个数组,主题的值将是 for 循环之后的所有标签作为字符串。因此,您的比较因单个标签而失败。以下代码应该适合您。
{% for product in collections.all.products %}
{% assign displayProduct = false %}
{% for tag in product.tags %}
{% if customer.tags contains tag %}
{% assign displayProduct = true%}
{% endif %}
{% endfor %}
{% if displayProduct == true %}
<a href="{{ product.url }}">
{% for image in product.images %}
<img src="{{ image.src | product_img_url: 'medium' }}">
{% endfor %}
<span>{{ product.title }}</span>
<span>{{ product.type }}</span>
</a>
{% endif %}
{% endfor %}
在上面的代码中,您遍历每个产品标签并查看客户标签数组是否包含相同的值。如果是这样,请将 displayProduct 设置为 true。使用标志变量而不是仅仅使用 if 条件来显示产品的原因是,如果用户和产品有多个相同的标签,这可以防止多次呈现相同的产品。
您可以通过仅在客户有一些标签时迭代产品来进一步改进这一点。