Shopify / liquid

Liquid markup language. Safe, customer facing template language for flexible web apps.
https://shopify.github.io/liquid/
MIT License
11.13k stars 1.39k forks source link

String to Object? #1808

Closed johnaweiss closed 5 months ago

johnaweiss commented 5 months ago

How can i treat string like an object, to iterate on nodes? If i do a for, then it iterates on every character. If i split on comma, it doesn't split at all.

I'm using this tool to evaluate my template. https://pramodvalavala-msft.github.io/liquid-playground/

My template:

  {
  {%- for item in answers -%}
    {{item.sublabels}}
  {%- endfor -%}
  }

My data:

{
    "answers": {
      "12": {
        "name": "administrativeContact",
        "order": "22",
        "sublabels": "{\"field_1\":\"First Name\",\"field_3\":\"Last Name\",\"field_4\":\"Phone\",\"field_5\":\"Title\"}",
        "text": "Administrative Contact",
        "type": "control_mixed",
        "answer": {
          "field_1": "John",
          "field_3": "White",
          "field_5": 1111111,
          "field_4": "111-111-1111"
        }
      },
      "22": {
        "name": "publicContact",
        "order": "24",
        "sublabels": "{\"field_2\":\"Street Address\",\"field_3\":\"Public phone number\",\"field_4\":\"Public email address\",\"field_6\":\"Hours of Operation\",\"field_7\":\"Website\",\"field_8\":\"Public email address\"}",
        "text": "Public Contact",
        "type": "control_mixed",
        "answer": {
          "field_2": "111 Ventura Blvd",
          "field_3": "111-111-1111",
          "field_8": "johnawhite@gmail.com",
          "field_7": "https://tort.xyz",
          "field_6": "10 am to 6 pm, M-F"
        }
     }
   }
}

Liquid output:

  {
    {"field_1":"First Name","field_3":"Last Name","field_4":"Phone","field_5":"Title"}
    {"field_2":"Street Address","field_3":"Public phone number","field_4":"Public email address","field_6":"Hours of Operation","field_7":"Website","field_8":"Public email address"}
  }
johnaweiss commented 5 months ago

Solved. There was an excess space in my split. This works:

  {
  {%- for item in answers -%}
    {%- assign oLabels = item.sublabels | Split: ',' -%}
    {%- for label in oLabels -%}
      {{label}}
    {%- endfor -%}
  {%- endfor -%}
  }