根据 laravel blade 视图中的 JSON 数据创建菜单

Creating menu from JSON data in laravel blade views

我正在尝试 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 文件本身有什么解决办法。

您必须调用 $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,但您不知道您将拥有多少个嵌套数组,则必须为子菜单 blade 创建额外的

<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>

然后您的菜单 blade 将如下所示:

<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 是否在所有条件中都是数组。