简体   繁体   English

将字符串放入数组 shopify 液体

[英]Put strings in arrays shopify liquid

In shopify there are products with metafields, which contain multiple numbers.在 shopify 中有带有元字段的产品,其中包含多个数字。 These numbers represent the fishing zones of the fish that is inside the product.这些数字代表产品内鱼类的捕捞区域。 For example, for product A the value is simply '27' and for product B the value is '27/48'.例如,对于产品 A,该值只是“27”,而对于产品 B,该值是“27/48”。 My way to go would be to create an array and put in values inside of this array.我的方法是创建一个数组并将值放入该数组中。 Something like this: If the metafield contains 27, then put 'Atlantic Ocean' inside of the array.像这样:如果元字段包含 27,则将“大西洋”放入数组中。 If the metafield contains 48, then put 'Pacific Ocean' inside of the array.如果元字段包含 48,则将“太平洋”放入数组中。 At the end I would print out the array.最后我会打印出数组。 Is this a good way to go or is there a better one?这是一个好方法还是有更好的方法? Thanks谢谢

I'm just assuming that saving "Atlantic Ocean" etc. in the Metafield as an array is not an option for you.我只是假设将 Metafield 中的“大西洋”等保存为数组不是您的选择。 So here's how I would approach this:所以这就是我将如何处理这个问题:

Create a global metafield that contains all definitions like so:创建一个包含所有定义的全局元字段,如下所示:

{
  "27": "Atlantic Ocean",
  "48": "Pacific Ocean"
}

Then, in liquid:然后,在液体中:

{%- liquid
  assign definitions = shop.metafields.namespace.key.value
  assign parts = product.metafields.namespace_key.key.value | split: '/'

  for part in parts
    echo definitions[part]

    unless forloop.index == parts.size
      echo ', '
    endunless
  endfor
-%}

This would render for product A:这将为产品 A 呈现:

Atlantic Ocean

And for product B:对于产品 B:

Atlantic Ocean, Pacific Ocean

This way you can easily update the definition JSON when you want to add a new type of ocean without updating the liquid source code.这样,当您想添加新类型的海洋时,您可以轻松更新定义 JSON,而无需更新液体源代码。

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

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