好吧,在这里我没有按照您的方法将类别放入选择框中,而是选择通过嵌套无序列表来描述它,但您也可以找到一种方法使其在选择框中也适用。
要解决多级类别渲染,您可以使用递归方法。在这里,我创建了一个blade模板文件,即categories.blade.php,代码如下:
类别.blade.php
<!-- Displaying the current category -->
<li value="{{ $category->id }}">{{ $category->name}}
<!-- If category has children -->
@if (count($category->children) > 0)
<!-- Create a nested unordered list -->
<ul>
<!-- Loop through this category's children -->
@foreach ($category->children as $sub)
<!-- Call this blade file again (recursive) and pass the current subcategory to it -->
@include('subcategories', ['category' => $sub])
@endforeach
</ul>
@endif
</li>
现在,在您的父刀片模板文件中,您可以包含categories.blade.php 文件,以循环遍历您的类别并显示它们。
...
<!-- Start an unoredered list -->
<ul>
<!-- Loop through each category -->
@foreach ($categories as $category)
<!-- Include subcategories.blade.php file and pass the current category to it -->
@include('subcategories', ['category' => $category])
@endforeach
<ul>
...
Here is an example that worked for me using the above technique:
Note 1:根据我的示例,假设categories.blade.php文件和父刀片文件位于同一文件夹中,如果您决定将它们放在不同的文件夹中,请确保在@include语句中输入正确的路径父刀片文件。
Note 2:据此:https://www.w3.org/TR/html401/interact/forms.html#h-17.6 https://www.w3.org/TR/html401/interact/forms.html#h-17.6,你不能嵌套optgroup标签相互嵌套,所以我建议您找到另一种方式来显示选择框。