Get one variant in Shopify

折月煮酒 提交于 2019-12-25 02:55:43

问题


My products have 2 variants, size and color. I want to display the size options as a series of buttons. Here's my current code:

{% for variant in product.variants %}
  <input type="button" name="{{ variant.id }}" id="{{ variant.id }}" value="{{ variant.title }}">
{% endfor %}

This returns buttons with values like S/White, M/White, L/White, etc. I want just S, M and L. Pulling from of the example code in the docs, I've tried

{% for variant in product.variants.size %}

and

{% for variant in product.variants.first %}

but evidently that's not the right syntax as nothing is output.

What's the correct way to do this?

TIA - Joe


回答1:


Variants contain up to 3 options. In your case, variant.option1 will give you the size (S/M/L) and variant.option2 is the colour. You can also get the titles of the options with product.options. See the doco here for more info on variants.

Also, have you seen this tutorial on adding colour swatches and buttons to a product page? Maybe some of the code for creating the buttons would help you get started.

EDIT:

By following the tutorial mentioned above, you can get buttons for the size options like this:

Put this code in product.liquid below </select>:

{% if product.available and product.variants.size > 1 %}
  {% include 'swatch' with 'Size' %}
{% endif %}

If you also want buttons for the color option (and not swatches), use this code in product.liquid:

{% if product.available and product.variants.size > 1 %}
  {% for option in product.options %}
    {% include 'swatch' with option %}
  {% endfor %}
{% endif %}

And delete these lines from swatch.liquid (line 30):

{% if downcased_option contains 'color' or downcased_option contains 'colour' %}
  {% assign is_color = true %}
{% endif %}


来源:https://stackoverflow.com/questions/24290313/get-one-variant-in-shopify

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!