Loading...

Thymeleaf使用递归来实现树

avatar

JimXu

2020-10-28

JAVA

Thymeleaf使用递归来实现树

最近被thymeleaf折磨的跟个鬼一样啊,就是多级树应该怎么遍历呢,关键是百度出来的看着也模模糊糊的,就知道了要使用th:fragment,开整

我先写个rest接口看看有哪些数据

1603845357278

只有3层,thymeleaf怎么实现呢,来看看代码

首先要创建一个模板html

<div th:fragment="tree(its,level)">
    <div class="item" th:class="${level eq 1 ? 'comment-content':'comment-content-level'}" th:each="it:${its}" >
        <div class="c1">
            <div class="img"> <img src="http://v7.jimxu.top/images/20201028none.png" alt="评论者头像"></div>
            <div class="message">
                <div class="name"><span th:text="${it.author}"></span></div>
                <span style="color: #888;">在留言</span>
            </div>
        </div>
        <div class="c2">
            <th:block th:if="${it.pname!=null}">
                <p th:text="'@'+${it.pname}+': '+${it.content}"></p>
            </th:block>
            <th:block th:if="${it.pname==null}">
                <p th:text="${it.content}"></p>
            </th:block>
        </div>
        <div class="btttn"><button name="submit" th:data-id="${it.coid}" th:data-name="${it.author}" class="reply" type="submit">回复</button></div>
        <div th:unless="${#lists.isEmpty(it.child)}" th:include="this::tree(${it.child},${level+1})"></div>
    </div>
</div>

这里我来一个一个解释吧

th:fragment="tree(its,level)"就是一个名为tree的模板,传入参数为its,level(its是list集合,level是层级) ${level eq 1 ? 'comment-content':'comment-content-level'}判断层级是否为第一层级,因为在我这里第一层级和后面的层级样式不一样,所以有这一步操作 th:each="it:${its}",这个都懂,就把list集合遍历一下 后面的一些都是我这里需要的参数

<div th:unless="${#lists.isEmpty(it.child)}" th:include="this::tree(${it.child},${level+1})"></div>

这句话就是如果当前遍历出来的it有子集合,就用这个模板把子集遍历了

然后看看需要树的地方怎么调用这个模板把

<th:block th:include="tree::tree(${comments},1)"></th:block>

传入所有的评论,然后层级为1。

就是这样了,虽然弄了半天,但还是弄好了呀,看看成品吧

1603846258102

Leave a message

tips:Your personal homepage URL will be publicly linked, but your email address will not be publicly displayed; your IP address will be saved, but only your current city name will be publicly displayed.

comment



Other article