【问题标题】:parse a string into tokens in Shopify Liquid在 Shopify Liquid 中将字符串解析为令牌
【发布时间】:2014-11-29 03:10:08
【问题描述】:

我在 Shopify 元字段中有以下字符串 ("my_str"):

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

键是产品变体 ID(缩写为 a、b、c...),数字是数量。

我需要将它解析成键值对,这样我就可以用它做这样的事情:

{% 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 %}

我绝对不知道如何解析 my_str。我也愿意接受有关整体最佳方法的建议。

【问题讨论】:

    标签: parsing shopify tokenize liquid


    【解决方案1】:

    Liquid 在创建数组方面非常有限。常用的方法是使用split string filter

    在你的情况下,它看起来像这样:

    {% 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 %}
    

    这篇博文也是关于 Liquid 数组主题的有趣读物:Advanced Arrays in Shopify's Liquid

    【讨论】:

      猜你喜欢
      • 2015-01-27
      • 1970-01-01
      • 2019-05-13
      • 2018-11-14
      • 2016-12-18
      • 2010-10-08
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多