Selecting a specific variant metafield

Highlighted
New Member
8 0 0

I'm trying to show metafields for the spefcific variant selected. 

A specific variant might have a release_date metafield with a value of 7/1/13, and another variant might have a release date of 7/12/13. 

I'm using OptionSelectors, so my javascript knows which atribute has been selected, but there seems to be know way to relate this to liquid. 

The following code will loop through the metafields for each variant of the product:

{% for variant in product.variants %}
{{ variant.metafields.product_info.release_date }}
{% endfor %}

Is there a way for me to tell liquid which attribute I have selected, so I can say somthing like: 

{% for variant in product.variants %}
{% if variant.id == this_variant_id %}
{{ variant.metafields.product_info.release_date }}
{% endif %}
{% endfor %}

Any ideas?

0 Likes
Highlighted
New Member
8 0 0

Sorry to resurrect a dead post, but I never received an answer to this. Anybody?

0 Likes
Highlighted
Shopify Expert
4125 29 383

This can be done using a very simple pattern. You use Liquid to render your variant's metafield into a data structure setup for Javascript. for eg: 

<script type="text/javascript">

  var variants = {};
  {% for variant in product.variants %}
    variants[{{variant.id}}] = "{{ variant.metafields.product_info.release_date }}";
  {% endfor %}

</script> 

So now you have a simple hash for your variants. Using Javascript you can now read the variant's metafield setting using the option_selector.js code. Since that code usually executes a callback function with the variant, you'll have the ID, hence the key to the hash, hence the metafield value, in this case a string representing a date. 

Now you can stick that date where the sun shines. Dead simple pattern...

 

Custom Shopify Apps built just for you! hunkybill@gmail.com http://www.resistorsoftware.com
2 Likes
Highlighted
New Member
8 0 0

Thanks @HunkyBill! I'll try this out! Much appreciated! I think this is a great solution!

0 Likes
Highlighted
Tourist
7 0 1

This solution seems like it should work, but for some reason it's not working :(

0 Likes