如何使用 thymeleaf 递归渲染菜单 [英] How to render menu using thymeleaf recursively

查看:89
本文介绍了如何使用 thymeleaf 递归渲染菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 ul/li 列表呈现 HTML 菜单.我有这个类结构:

I would like to render HTML menu using ul/li list. I've got this class structure:

public class MenuItem {

    private String name;

    private MenuItem parent;

    private List<MenuItem> children;

    public MenuItem(String name,List<MenuItem> children) {
        this.name = name;
        this.children = children;
        for (MenuItem child : children) {
            child.parent = this;
        }
    }

    public MenuItem(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public MenuItem getParent() {
        return parent;
    }

    public List<MenuItem> getChildren() {
        return children;
    }
} 

如您所见,这是典型的树结构,其中一个根元素包含对其子元素的引用,而它们又引用了它们的子元素等等.

As you can see it's typical tree structure, in which one root element contains reference to its children and they have reference to theirs and so on.

现在我想渲染这样的结构:

Now I would love to render structure like this:

<ul>
    <li>Item 1
        <ul>
            <li>Item 1.1</li>
            <li>Item 1.2
                <ul>
                    <li>Item 1.2.1</li>
                    <li>Item 1.2.3</li>
                </ul>
            </li>
            <li>Item 1.3</li>
        </ul>
    </li>
    <li>Item 2</li>
</ul>

如何用百里香叶做到这一点?如果我必须使用其他技术,例如瓷砖、布局或其他任何东西,我很容易.

How can I do that with thymeleaf? I'm easy if I have to use other technologies like Tiles, Layout or anything else.

我尝试了参数化的包含/替换,但没有成功.传递的参数被转换为 String 并且不能用于另一个级别的递归.请参阅 https://github.com/ultraq/thymeleaf-layout-dialect/issues/12

I tried parameterized include/replace but with no luck. Parameters passed through are converted to String and can't be used for another level of recursion. See https://github.com/ultraq/thymeleaf-layout-dialect/issues/12

非常感谢,

弗兰克

推荐答案

试试这个:

为单个菜单项创建一个片段为 menuFragment.html

Create a fragment for single menu item as menuFragment.html

<html>
    <section layout:fragment="menu">
        <ul>
            <li th:each="menuItem : ${menuItemsList}" th:text="${menuItem.name}">
                <section layout:include="@{path/to/folder/menuFragment} :: menu" th:with="menuItemsList=${menuItem.children}"></section>
            </li>
        </ul> 
    </section>
</html>

在菜单文件中包含片段

<section layout:include="@{path/to/folder/menuFragment} :: menu" th:with="menuItemsList=${rootMenuItemAsList}"></section>

rootMenuItemAsList 是一个带有父菜单的列表

rootMenuItemAsList is a list with your parent menu

希望对你有帮助

这篇关于如何使用 thymeleaf 递归渲染菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆