V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ufan0
V2EX  ›  Java

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

  •  
  •   ufan0 · 2020-01-03 02:23:29 +08:00 · 2746 次点击
    这是一个创建于 1546 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    第 1 条附言  ·  2020-01-11 19:33:02 +08:00
    楼里关于 Thymeleaf 的用法其实我都知道,谢谢你们的回复;

    关于这个问题的解决办法,其实就是用拦截器传值罢了;

    怪我的问题描述不清楚,在这里向各位抱歉。
    7 条回复    2020-01-03 08:54:06 +08:00
    ysyk
        1
    ysyk  
       2020-01-03 08:10:01 +08:00   ❤️ 1
    是的,可以。与引用的页面其他参数相同。
    ysyk
        2
    ysyk  
       2020-01-03 08:11:16 +08:00   ❤️ 1
    我的写法 <div th:replace="header :: footer"></div>

    <div th:fragment="footer">

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

    我是想知道后台对 fragment 传值😂,因为剥离了多个页面的公共部分至 fragment,但是有些参数得传至 fragment,比如页面 title、description,若是每个 url 映射都写个 model.addAttribute()就太难看了;
    Andy00
        4
    Andy00  
       2020-01-03 08:40:49 +08:00   ❤️ 1
    可以,刚刚用了这功能。像调用函数一样往需要传参数的 fragment 里放入参数就行了,参考我的代码
    ```html
    <div th:replace="commons/bar::sidebar(activeURI='kpi', employees=${employees})"></div>
    ```
    employees 是一个在 model 里传过来的 list
    Andy00
        5
    Andy00  
       2020-01-03 08:42:40 +08:00   ❤️ 1
    咦居然不支持代码标签。
    activeURI 和 employees 就是两个传到 sidebar fragment 里的参数
    iwiki
        6
    iwiki  
       2020-01-03 08:49:59 +08:00 via iPhone   ❤️ 1
    <!-- 菜单递归 -->
    <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
        7
    ysyk  
       2020-01-03 08:54:06 +08:00   ❤️ 2
    Controller 里这样写
    @ModelAttribute("helper")
    public Helper helper() {
    return helper;
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3169 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:20 · PVG 20:20 · LAX 05:20 · JFK 08:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.