【问题标题】:is it correct to use th:replace/th:insert without using fragments?在不使用片段的情况下使用 th:replace/th:insert 是否正确?
【发布时间】:2020-05-14 23:59:04
【问题描述】:

我是 Thymeleaf 的新手,我想知道标签 th:insertth:replace 是否绝对需要引用片段。

这是一个例子,我想在父模板中包含整个页面menu.html

<!DOCTYPE html>
<html>
   <body>
      <th:block th:replace="child/menu"></th:block>
   </body>
</html>

这里是子菜单模板menu.html

 <ul>
    <li>Menu 1</li>
    <li>Menu 2</li>
 </ul>

它工作正常,但我在文档中没有找到任何这样的例子,每个对 th:replace 的引用都使用像这样的片段调用th:replace="child/menu :: menu",所以我想知道是否我的代码是正确的

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

    您的代码很好。简单的证明是尝试在可嵌入页面中使用 Thymeleaf 表达式:

    <ul>
        <li th:text="${attrValue}"></li>
    </ul>
    

    如果您在初始模板中传递 attrValue 模型属性,这将毫无问题。您甚至不必在 menu.html 页面中指定 Thymeleaf 架构 URL。

    【讨论】:

    • 是的,我知道它有效,我目前正在使用它并且没有错误。在文档中,他们系统地将th:replace 与片段一起使用,所以我想知道我的代码是否符合框架并且不是一个坏习惯
    • 也许您应该只在 Thymeleaf 架构 URL 中添加 HTML 标记,以便现代 IDE 可以识别 Thymeleaf 表达式。但我看不出你的方法有什么特别的问题。
    【解决方案2】:

    这是一个可以理解的例子 假设这是片段

    我们在这些 div 中使用这个

    所以最终输出:

     <div id="tagWithFragmentAttribute">
         <div id="contentGoesHere"></div>
        </div>
    
        <div id="tagWithInsertAttribute">
         <div id="tagWithFragmentAttribute">
          <div id="contentGoesHere"></div>
         </div>
        </div>
    
        <div id="tagWithIncludeAttribute">
         <div id="contentGoesHere"></div>
        </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多