1
Array
(
    [page_title] => Slovak RS
    [page_footer] => © Copyright 2017
    [is_published] => published
    [menu] => {
    "id":"1",
    "name": "main_menu",
    "items": [
        "pos1": [
        "display_name" : "Informácie",
        "path"         : "informacie"
    ],
        "pos2": [
        "display_name" : "Videá",
        "path"         : "video"
    ],
        "pos4": [
        "display_name" : "Recepty",
        "path"         : "recepty"
    ],
        "pos5": [
        "display_name" : "Galéria",
        "path"         : "galeria"
    ],
        "pos6": [
        "display_name" : "Osobnosti",
        "path"         : "osobnosti"
    ],
    ],
    "updated_at": "2020"
 }
)

This is data I'm getting into twig template file. I want to have menu in single db table stored as json. I can show items like {{ menu }}, {{ page_title }}, but have hard times looping through that json part

This is what i tried

 {% for item in menu %}
    {{ item.id }}
    {{ item['id'] }}
    {% endfor %}

    {% for key,value in menu %}
    Key : {{ key }}
    Value : {{ value }}
    {% endfor %}

I'm using twig 2.x and I'm newbie

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Matej Vrzala M4
  • 1,364
  • 2
  • 13
  • 20
  • is not possible decode in the twig template, see [this](http://stackoverflow.com/a/14504988/2270041) solutions if is good for you – Matteo Feb 06 '17 at 09:15

1 Answers1

1

You should json_decode the JSON first, before you're passing it to twig. With that, you have an array or object, that you can loop through.

$objJson = json_decode($yourDBArray['menu']);
$arrJson = json_decode($yourDBArray['menu'],true);

In the code you've provided, the JSON is a string and not an array nor an object.

KhorneHoly
  • 4,666
  • 6
  • 43
  • 75