简体   繁体   中英

Put strings in arrays shopify liquid

In shopify there are products with metafields, which contain multiple numbers. 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'. 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. If the metafield contains 48, then put 'Pacific Ocean' inside of the array. 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. 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:

Atlantic Ocean

And for product 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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