【问题标题】:How to add iterations on this liquid for loop如何在这种液体 for 循环上添加迭代
【发布时间】:2018-12-18 15:56:16
【问题描述】:

我如何添加一个在这个 for 循环上迭代的数字来代替 {{i}} 请注意,此循环没有特定限制,因为它会获取所有订购的商品,无论它们有多少。

<img src="https://billiger.de/sale?shop_id=Acaraa&oid={{ order.order_number }}

{% for line_item in order.line_items %}
&aid_{{i}}={{ line_item.product_id }}&name_{{i}}={{ line_item.product.title }}&cnt_{{i}}={{ line_item.quantity }}&val_{{i}}={{ line_item.product.price | divided_by: 1.19  | times: line_item.quantity | money_without_currency}}
{% endfor %}

" width="1" height="1" border="0" alt="" />

所以循环应该是这样的

&aid_1=ARTICLE-ID-1&name_1=ARTICLE-NAME-1&cnt_1=ARTICLE-COUNT-1&val_1=ARTICLE-VALUE-1
&aid_2=ARTICLE-ID-2&name_2=ARTICLE-NAME-2&cnt_2=ARTICLE-COUNT-2&val_2=ARTICLE-VALUE-2
&aid_3=ARTICLE-ID-3&name_3=ARTICLE-NAME-3&cnt_3=ARTICLE-COUNT-3&val_3=ARTICLE-VALUE-3

PS:以上代码将在shopify模板文件中使用

谢谢

【问题讨论】:

  • 我认为这是 Shopify 用于 Ruby 的 Liquid 模板库的 PHP 端口?如果是这样,如果端口是完整的,我认为它应该有forloop.index(或它的零索引对应部分index0)。
  • 我不会发布答案,因为我假设您使用的是移植库 - 但我不知道 Google 上哪一个为我提供了帮助。你能提供图书馆的链接吗?
  • @DarraghEnright 很抱歉,我没有提到我的问题是我的问题与 Shopify 模板液体文件有关
  • 没问题,但是您使用的是 PHP 端口,对吗? Is this it?

标签: php html shopify liquid liquid-layout


【解决方案1】:

forloop 对象有许多辅助方法,包括用于计算循环当前迭代次数的方法:

  • forloop.index 从 1 开始计算循环迭代
  • forloop.index0 从 0 开始计算循环迭代

在您的示例中,您将修改代码以使用适当的方法而不是{{i}};即:

<img src="https://billiger.de/sale?shop_id=Acaraa&oid={{ order.order_number }}

{% for line_item in order.line_items %}
&aid_{{forloop.index}}={{ line_item.product_id }}&name_{{forloop.index}}={{ line_item.product.title }}&cnt_{{forloop.index}}={{ line_item.quantity }}&val_{{forloop.index}}={{ line_item.product.price | divided_by: 1.19  | times: line_item.quantity | money_without_currency}}
{% endfor %}

" width="1" height="1" border="0" alt="" />

我假设您想在这里从1 开始计算迭代次数,但如果您想从0 开始,只需使用forloop.index0。

Here is the documentation for forloop.index 用于 Shopify 的官方 Liquid 库(在 Ruby 中)。

由于您已将问题标记为 PHP,因此您似乎正在使用库的 php-liquid 端口 - 它出现在 Shopify 的 Liquid ports 列表中。

这个端口似乎没有任何详细的文档,但是如果您查看unit tests,您会发现这些 forloop 帮助程序已经实现。

希望这会有所帮助:)

【讨论】:

  • 糟糕!修正了代码中的一个错字——我写了foreach.index,而我本来打算写forloop.index。现在修复:)
  • 非常感谢您的回答,它对我来说非常有用:)
  • 我很高兴,很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 2011-05-14
  • 2017-03-05
  • 2015-01-14
  • 2021-12-27
  • 2018-05-23
相关资源
最近更新 更多