简体   繁体   中英

Twig loop through JSON

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

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 .

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