简体   繁体   中英

How to access array variable from a twig file

I have a controller which returns all menus. From twig file, i use to access controller to get all menus.

I could just see all my menus in my twig file.

Code:

Twig File :

{% set menulist%}{%render url('get_all_menus')%}{% endset %}

I use for loop to print my menu name. Like

{% for menu in menulist %}

    {{menu.MenuName}}

{%endfor%}

But I don't get any values from the above for loop. When I use dump(menu-list) I get result as

[{"FunctionName":"Home","ModuleName":null,"SubModuleName":null,"PageURL":"home_page","AccessLevel":"2"}]

Which is a JSON data that I return from my controller. How can i get the values from my for loop? Am i making any mistake here?

Why you are rendering another controller? It performs second request to application. Create custom twig function to return menu elements -> http://symfony.com/doc/current/cookbook/templating/twig_extension.html
That will be faster and JSON problem should disappear. Or if you don't want to create twig function - render partial menu twig file in controller action with name 'get_all_menus'.

You need to store menu result in one variable like below :

And used json_decode function for convert your json data into array than you can get your menu data through loop.

$menuJsonData = '[{"FunctionName":"Home","ModuleName":null,"SubModuleName":null,"PageURL":"home_page","AccessLevel":"2"}]';

$menuData = json_decode($test);

foreach($menuData as $menu){
    echo $menu->FunctionName;
}

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