d
Topic
Posts:
3
Last edited February 10, 2015

Problem accessing metafields in Liquid This post is outdated

Hey everyone.

I'm having an issue with metafield access in liquid. I have a metafield namespace "name" that I'd like to iterate through, and I'd like to use the key at each iteration for accessing values in other namespaces. For example, I want to grab a photo url that corresponds to one of the names, so I do:

{% for member in page.metafields.name $}
        {% capture key %} '{{ member | first }}' {% endcapture %}
        <img src="{{ page.metafields.image_urls[key] }}" />
{% endfor %}

This doesn't work, however. I printed some stuff out to test it:

        {% assign key2 = 'cool_guy' %}
        {{ key}}, {{ key2 }}
        {% if key == key2 %}
          <p>true</p>
        {% endif %}

If I print out each key they look identical, but only the directly assigned key2 grabs the image properly. The 'if' clause evaluates as false.

What am I missing? Thanks in advance!

i
Replies
Posts:
437
February 10, 2015

Try removing the leading and trailing space and single quote when capturing your key.

{% capture key %}{{ member | first }}{% endcapture %}

Shopify Design, Development &amp; Maintenance // 3five.com
Posts:
3
February 10, 2015

Hi gina3five,

I appreciate the quick response! That was actually the first method I tried...I've tried all permutations of quote options at this point. 

Please keep the ideas coming :)

R,
Cory

Posts:
437
Last edited February 10, 2015

Assuming you have your metafields set up something like this:

page.metafields.name.bob, value = Robert
page.metafields.name.frank, value = Franklin

page.metafields.image_url.bob, value = bob.jpg
page.metafields.image_url.frank, value = frank.jpg

This:

{% for member in page.metafields.name $}
        {% capture key %}{{ member | first }}{% endcapture %}
        {% capture value %}{{ member | last }}{% endcapture %}
        <img src="{{ page.metafields.image_url[key] }}" />
        <h3>{{ value }}</h3>
{% endfor %}

Should give you this:

<img src="bob.jpg" />
<h3>Robert</h3>

<img src="frank.jpg" />
<h3>Franklin</h3>

Shopify Design, Development &amp; Maintenance // 3five.com
Posts:
3
Last edited February 10, 2015

Hey Gina,

Your key point that I totally misunderstood was that it was capturing the spaces and putting the key in between them. Makes perfect sense and now works.

Thanks much!
Cory