3
votes

Was first looking for a means to select certain existing products in order to place title, image, description on another page (or even within another product page - as some products are combined to make other products) within Shopify.

The method below was the only one I seem to come across for creating an array within Shopify. (the split method).

The next part of the equation, is to use the values from {{ myArray }}, to select the matching var, and to then spit out the different values stored within that array.

However, my attempt does not work. Is there a way to add keys to the other arrays (i.e, p1, p2, p3 arrays), in order to make the selecting of them easier during the for loop?

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

2 Answers

10
votes

Continuity flow is wrong in your code.

Here's what you need to do

  1. Load product elements for each product into an array

    {% 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. Now p_list contains all the products as each element in the array. It is time to get the output.

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

Once you start the for loop it will iterate through each value in your array, so indexing (using []) won't work since the array is already being iterated.

In the example above, you began iterating through the list and then attempted to index item, which will not work. If you wanted to index the array then do not make a for loop, in the list above the array only has 2 items but you selected an index outside of the available indexes, this is because the array position starts at 0. so that <p> tag should've been item[1] and outside of the for loop.

To do a for loop. do this:

{% for item in array %}
   <h4>{{ item }}</h4>
   {{ continue }}
   <p>{{ item }}</p>
{% endfor %}

The continue tag will cause it to iterate to the next item on the for loop.