在laravel刀片视图中从JSON数据创建菜单

时间:2016-08-10 05:48:40

标签: php json laravel menuitem submenu

我尝试multi level menuJSON data,以下是我的JSON格式数据:

{"pages": [
        {"pagelink": "index.html", "pagename": "Mysite", "submenu": [
                    {"pagelink": "#", "pagename": "sublevel1", "submenu": "NULL"},
                    {"pagelink": "#", "pagename": "submenu2", "submenu": [

                        {"pagelink": "#", "pagename": "sublevel2", "submenu": "NULL"}

                        ]
                    }
                ]
        }, 
        {"pagelink": "templates.html", "pagename": "Templates", "submenu": "NULL"}, 
        {"pagelink": "aboutus.html", "pagename": "About Us", "submenu": "NULL"}, 
        {"pagelink": "contactus.html", "pagename": "Contact Us", "submenu": "NULL"}
    ]
}

当我没有sub menu字段时,我曾经按照以下方式调用菜单:

<nav id="nav">
    <ul id="main-nav" class="hidden-mobile">
        @foreach($contents->pages as $pages)
            <li class="menu-item-has-children">
                <a href="{{ $pages->pagelink }}">{{ $pages->pagename }}</a>
            </li>
        @endforeach
    </ul>
</nav>

当我添加子菜单时,我尝试使用以下代码:

<nav id="nav">
    <ul id="main-nav" class="hidden-mobile">
        @foreach($contents->pages as $pages)
            <li class="menu-item-has-children">
                <a href="{{ $pages->pagelink }}">{{ $pages->pagename }}</a>
                @if(isset($contents->pages->submenu))
                     <ul class="sub-nav">
                        @foreach($contents->pages->submenu as $submenu)
                            <li><a href="{{ $submenu->pagelink }}">{{ $submenu->pagename }}</a> </li>
                        @endforeach
                     </ul>
                @endif
            </li>
        @endforeach
    </ul>
</nav>

但它没有成功。

请指导我,我是否需要更改JSON data格式,或blade文件本身是否有任何出路。

1 个答案:

答案 0 :(得分:2)

您必须致电$pages,而不是$contents->pages

@if(isset($pages->submenu))
    <ul class="sub-nav">
        @foreach($pages->submenu as $submenu)
            <li><a href="{{ $submenu->pagelink }}">{{ $submenu->pagename }}</a> </li>
        @endforeach
    </ul>
@endif

如果您想创建多维JSON,并且您不知道,您将拥有多少嵌套数组,则必须为子菜单创建额外的刀片

<ul class="sub-nav">
    @foreach($pages as $submenu)
        <li>
            <a href="{{ $submenu->pagelink }}">{{ $submenu->pagename }}</a>
            @if (isset($submenu->submenu))
                @include('submenu', ['pages' => $submenu->submenu])
            @endif
        </li>
    @endforeach
</ul>

然后您的菜单刀片将显示为:

<nav id="nav">
    <ul id="main-nav" class="hidden-mobile">
        @foreach($contents->pages as $pages)
            <li class="menu-item-has-children">
                <a href="{{ $pages->pagelink }}">{{ $pages->pagename }}</a>
                @if(isset($pages->submenu))
                    @include('submenu', ['pages' => $pages->submenu])
                @endif
            </li>
        @endforeach
    </ul>
</nav>

如果您要移除"submenu": "NULL",此解决方案应该有效。如果没有,则必须另外检查,如果元素submenu是所有条件中的数组。