Shopify - 循环模式中的数据

标签 shopify liquid

在尝试创建 Shopify 主题时,我在创建循环时遇到了问题。

我允许主题管理员从 1 到 4 种产品中选择要在商店中展示的产品。他可以从他的主题的自定义 UI 中选择它们。

架构是:

{
  "type": "product",
  "id": "popular_product_1",
  "label": "Product N°1"
},
{
  "type": "product",
  "id": "popular_product_2",
  "label": "Product N°2"
},
{
  "type": "product",
  "id": "popular_product_3",
  "label": "Product N°3"
},
{
  "type": "product",
  "id": "popular_product_4",
  "label": "Product N°4"
}

回到我的 liquid 文件,作为测试,如果我想要产品的 URL,我可以这样做:

{{ all_products[section.settings.popular_product_1].url }}

而且它会起作用。但当然,我必须重复相同的代码 4 次。所以我想创建一个遍历每个循环的循环。

但是如何获取上面要插入的增量数呢? 当然

{{ all_products[section.settings.popular_product_i].url }}
{{ all_products[section.settings.popular_product_{{i}}].url }}

不工作。

我也试过

{% assign i = 1 %}
{% capture popular_product %}section.settings.popular_product_{{i}}{% endcapture %}
{{ all_products[popular_product].url }}

但它也不起作用...因为变量 popular_product 似乎是一个字符串,但它不是它应该的样子。

最佳答案

替代方法:使用节 block

您是否考虑过在基本设置中使用带有 block 的部分,而不是仅仅使用编号的产品字段?如果您创建一个“热门产品”部分并定义热门产品 block ,您可以添加任意数量的产品(或可以指定最大值),然后使用

遍历它们
{% for block in section.blocks %} 
   {% assign popular_product = all_products[block.settings.product] %}
   <!-- Cool stuff with your popular product -->
{% endfor %}

您可以在此处阅读有关在 Shopify 中设置部分和 block 的更多信息:https://help.shopify.com/en/themes/development/sections


现在,您使用的方法并没有错,但是您上面的代码有一些错误。这些可以更正以获得正确的产品句柄以用于 all_products 查找。第一:

{{ all_products[section.settings.popular_product_{{i}}].url }}

是不正确的:我们从不在 Liquid 花括号内嵌套 Liquid 花括号。相反,这应该类似于:

{% for i in (1..4) %}
  {% assign setting_name = 'popular_product_' | append: i %}
  {% assign handle = section.settings[setting_name] %}
  {% assign popular_product = all_products[handle] %}
  <!-- Cool stuff with our popular_product object -->
{% endfor %}

接下来,capture 变量将计算标签之间的所有内容并将其存储在字符串中。当您使用时:

{% capture popular_product %}section.settings.popular_product_{{i}}{% endcapture %}

抓取的内容是先代入i的值,然后抓取结果字符串,不是产品句柄!您真正想要的是 section.settings 对象中的特定值。

您应该使用 capture 来获取您需要的 popular_product_x 变量,并在 section.settings 中访问它。例如:

{% capture field_name %}popular_product_{{i}}{% endcapture %}
{% assign popular_product = all_products[section.settings[field_name]] %}
<!-- Cool stuff with your popular product -->

希望这对您有所帮助!


注意:我个人更喜欢assign 用于像上面这样的简单变量,而使用capture 仅用于抓取多行(如 HTML block ) ),但在这种情况下,任何一个都有效。 capture 的警告:请记住,所有空格也会被捕获,这对于产品句柄或设置名称等简单变量通常是无意的。

希望这对您有所帮助!

关于Shopify - 循环模式中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55475715/

相关文章:

html - Shopify 的 SVG Sprite 解决方法

javascript - 从事件类中获取值并假设为另一个

Shopify:如何确保我的应用程序代理内容适用于所有模板?

html - 基于屏幕尺寸的木材 Shopify 主题推/拉列

yaml - 从 Jekyll 数据文件中的 yaml 多行字符串渲染 Markdown

api - 通过 Shopify API 获取产品列表时,分页在服务器端如何工作?

shopify - 向 Shopify 液体链接添加类?

shopify - 如何将自定义 html block 添加到页脚选项列表?

html - 如何在 Shopify 中自定义收藏集?

java - Java/Scala 中的液体标记