简体   繁体   English

在Shopify Liquid中将字符串解析为令牌

[英]parse a string into tokens in Shopify Liquid

I have the following string ("my_str") in a Shopify metafield: 我在Shopify元字段中具有以下字符串(“ my_str”):

a:3,b:1,c:2,d:2,e:2,f:2

The keys are product variant IDs (shortened to a, b, c...) and the numbers are quantities. 键是产品型号ID(缩写为a,b,c ...),数字是数量。

I need to parse it into key:value pairs so I can do something like this with it: 我需要将其解析为key:value对,以便可以执行以下操作:

{% assign my_str = collection.metafields.local.my_metafield %}
{% assign my_map = my_str | parse ???? %}

{% for product in collection.products %}
    {% assign temp_qty = 1 %}
    {% for pair in my_map %}
        {% if pair[0] == product.variants.first.id %}
          {% assign temp_qty = pair[1] %}
        {% endif %}
    {% endfor %}
    <input type="hidden"  id="abc-{{ forloop.index0 }}" value=temp_qty />
{% endfor %}

I definitely don't know how to parse my_str. 我绝对不知道如何解析my_str。 I'm also open to suggestions about the best approach overall. 我也乐意接受有关最佳总体方法的建议。

Liquid is pretty limited when it comes to creating arrays. 在创建数组时,Liquid非常有限。 The common approach is to use the split string filter . 常用的方法是使用split字符串过滤器

In your case, it would look something like this: 就您而言,它看起来像这样:

{% assign my_str = 'a:3,b:1,c:2,d:2,e:2,f:2' %}
{% assign my_arr = my_str | split: ',' %}

{% for pair_str in my_arr %}
  {% assign pair_arr = pair_str | split: ':' %}
  ID: {{ pair_arr[0] }} Qty: {{ pair_arr[1] }} <br />
{% endfor %}

This blog post is also an interesting read on the topic of Liquid arrays: Advanced Arrays in Shopify's Liquid 这篇博客文章也是关于Liquid数组主题的有趣读物: Shopify的Liquid中的高级数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM