在液体模板中创建和访问数组

时间:2014-08-15 23:04:05

标签: shopify liquid

首先寻找一种方法来选择某些现有产品,以便在Shopify中将标题,图像,描述放在另一个页面上(甚至在另一个产品页面中 - 因为某些产品被组合成其他产品)。

以下方法是我在Shopify中创建数组时遇到的唯一方法。 (分割方法)。

等式的下一部分是使用{{myArray}}中的值来选择匹配的var,然后吐出存储在该数组中的不同值。

然而,我的尝试不起作用。有没有办法将键添加到其他数组(即p1,p2,p3数组),以便在for循环期间更容易选择它们?

{% assign myArray = "p1|p3" | split: "|" %}

{% assign p1 = "Product One|product-one|This is my description of product one, and it must be a single paragraphy without any html formatting. The length is not an issue.|product_one_image.jpg" | split:"|" %}

{% assign p2 = "Product Two|product-two|This is my description of product two, and it must be a single paragraphy without any html formatting.|product_two_image.jpg" | split:"|" %}

{% assign p3 = "Product Three|product-three|This is my description of product three, and it must be a single paragraphy without any html formatting.|product_three_image.jpg" | split:"|" %}

{% for item in myArray %}
    <h4>{{ item[0] }}</h4>
    <p>{{ item[2] }}</p>
{% endfor %}

2 个答案:

答案 0 :(得分:10)

代码中的连续性流是错误的。

这是你需要做的事情

  1. 将每个产品的产品元素加载到数组中

    {% capture list %}
        {% for product in products %}
        {{ product.title }}|{{ product.handle }}|{{ product.description}}|{{ product.featured_image }}{% if forloop.last %}^{% endif %}
        {% endfor %}
    {% endcapture %}
    {% assign p_list = list | split: "^" %}
    
  2. 现在p_list包含数组中每个元素的所有产品。是时候获得输出了。

    {% for p_item in p_list %}
        {% assign item = p_item | split: "|" %}
        <h4>{{ item[0] }}</h4>
        <p>{{ item[2] }}<p>
    {% endfor %}
    

答案 1 :(得分:1)

一旦启动for循环,它将遍历数组中的每个值,因此索引(使用[])不会起作用,因为数组已经被迭代了。

在上面的示例中,您开始遍历列表,然后尝试索引项目,这将无效。如果你想索引数组然后不做一个for循环,在上面的列表中,数组只有2个项目,但你选择了一个可用索引之外的索引,这是因为数组位置从0开始。所以{{ 1}}标签应该是项目[1]并且在for循环之外。

做一个for循环。这样做:

<p>

continue标记将使其迭代到for循环中的下一个项目。

相关问题