Thymeleaf 中,后台能对 fragment 传值吗?

2020-01-03 02:23:29 +08:00
 ufan0

Spring boot 程序中,后台对 thymeleaf 视图传值我知道, 控制方法里 model.addAttribute()就行了,但是能否对 fragment 传值呢?

未找到有帮助的信息,故发帖询问,感激不尽。

2782 次点击
所在节点    Java
7 条回复
ysyk
2020-01-03 08:10:01 +08:00
是的,可以。与引用的页面其他参数相同。
ysyk
2020-01-03 08:11:16 +08:00
我的写法 <div th:replace="header :: footer"></div>

<div th:fragment="footer">

</div>
ufan0
2020-01-03 08:29:34 +08:00
@ysyk #2 首先感谢回复,应该是我没表达清楚想询问的点;

我是想知道后台对 fragment 传值😂,因为剥离了多个页面的公共部分至 fragment,但是有些参数得传至 fragment,比如页面 title、description,若是每个 url 映射都写个 model.addAttribute()就太难看了;
Andy00
2020-01-03 08:40:49 +08:00
可以,刚刚用了这功能。像调用函数一样往需要传参数的 fragment 里放入参数就行了,参考我的代码
```html
<div th:replace="commons/bar::sidebar(activeURI='kpi', employees=${employees})"></div>
```
employees 是一个在 model 里传过来的 list
Andy00
2020-01-03 08:42:40 +08:00
咦居然不支持代码标签。
activeURI 和 employees 就是两个传到 sidebar fragment 里的参数
iwiki
2020-01-03 08:49:59 +08:00
<!-- 菜单递归 -->
<th:block th:fragment="listmenu(menus)">
<th:block th:each="menu : ${menus}">
<th:block th:if="${menu.getMenus().size()>0}">
<li class="nav-item has-treeview">
<a href="#" class="nav-link">
<i class="nav-icon fas fa-tachometer-alt"></i>
<p>
<span th:text="${menu.getName()}"></span>
<i class="right fas fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<th:block th:include="this::listmenu(${menu.getMenus()})"/>
</ul>
</li>
</th:block>
<th:block th:if="${menu.getMenus().size()==0}">
<li class="nav-item">
<a href="#" th:href="${menu.getUri()}" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p th:text="${menu.getName()}"></p>
</a>
</li>
</th:block>
</th:block>
</th:block>

参考这个吧,函数传值
ysyk
2020-01-03 08:54:06 +08:00
Controller 里这样写
@ModelAttribute("helper")
public Helper helper() {
return helper;
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/634625

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX