skip to Main Content

Is there any way to call metafields image positions in variants? It works fine in liquid obviously, but I have one function which needs the data as well, but can only be loaded from javascript. I don’t have a problem getting variant.id or featured_image, however metafields I just don’t know what to do.
The liquid code (simplified) which fetches image positions is:

                      {%- for variant in product.variants -%}
                    <option data-image-positions="{{variant.metafields.variant.image_position}}">
                    </option>
                  {%- endfor -%}

Would appreciate some pointers.

2

Answers


  1. JS always renders AFTER Liquid. So use Liquid to render values into your JS, and then you can freely use JS to do as you wish. Has always been a thing you can do.

    Login or Signup to reply.
  2. You could do something like this, you can add below script in to markup

    <script>
    // variable holding id and size details
    const imagePositions = [];
    
    // loop
    {%- for variant in product.variants -%}
    
      // pushing data what we need
      imagePositions.push({
        id: {{variant.id}},
        image_position: {{variant.metafields.variant.image_position}}
        // if position is in string use quotes '{{variant...}}'
      });
    {%- endfor -%}
    
    // you can use imagePositions array to anywhere in js 
    console.log(imagePositions);
    </script>
    

    Your output will be

    [
      {
        id: 1,
        image_position: 100 // your position
      },
      {
        id: 2,
        image_position: 200 // your position
      }
    ]
    

    if any doubt please comment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search