【问题标题】:What type of operation and syntax for them are possible on Thymeleaf 3 fragment expression?Thymeleaf 3 片段表达式可以进行哪些类型的操作和语法?
【发布时间】:2017-12-24 06:48:10
【问题描述】:

使用 Thymeleaf 3,可以通过 ~{:: selector} 语法将片段从页面传递到模板。

对该对象可以进行什么样的操作?

Fragment 可以在表达式中使用:

<div th:fragment="name(arg)">
  <div th:replace="${arg} :? _"></div>
</div>

我可以只提取片段内的部分片段吗(以下是不正确的语法!!):

<div th:fragment="name(arg)">
  <div th:replace="${arg :: script} :? _"></div>
  <div th:replace="${arg}.filter('script'} :? _"></div>
  <div th:replace="${xpath(${arg},'script')} :? _"></div>
</div>

更新我反省了用什么片段表达式来解决:

<th:block th:text="${bodyContent.class}" />

这是org.thymeleaf.standard.expression.Fragment。它有:

<th:block th:text="${bodyContent.templateModel.class}" />

TemplateModel 可以通过toString()write(Writer writer) 渲染。我看不到过滤Fragment 内容的简单方法...

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    我看到了我尝试使用的Thymeleaf templates - Is there a way to decorate a template instead of including a template fragment? 技术。

    Thymeleaf v2.1 和 3 允许将模板/片段组合引用到自身。

    让我们看看模板:

    <html lang="en" xmlns:th="http://www.thymeleaf.org">
        <body>
           <nav></nav>
           <div th:replace="this :: body"/>
        </body>
    </html>
    

    到页面:

    <html lang="en" xmlns:th="http://www.thymeleaf.org"
          th:replace="thymeleaf/layout/default :: html">
        <body>
           XXX
        </body>
    </html>
    

    以上代码生成&lt;body&gt;&lt;nav&gt;&lt;/nav&gt; 的无限序列,作为从模板引用到body 模板的CSS 选择器。

    为了移动对页面的引用,我添加了更复杂的 CSS 样式选择器:

    <html lang="en" xmlns:th="http://www.thymeleaf.org" class="htmlFrag">
        <body>
           <nav></nav>
           <div th:replace="this :: html[!class]/body"/>
        </body>
    </html>
    

    我不确定如何使模板和页面在同一范围内进行选择器匹配,但它可以工作...

    使用 CSS/JS 处理的高级模板可以表示为:

    <html lang="en" xmlns:th="http://www.thymeleaf.org" class="htmlFrag">
        <head>
           <meta charset="UTF-8">
           <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
           <title th:text="~{::html[!class]/head/title/text()}"></title>
    
           <link rel='stylesheet' href='/webjars/...">
           <div th:replace="this :: html[!class]/head/link"/>
    
           <script src="/webjars/..."></script>
           <div th:replace="this :: html[!class]/head/script"/>
        </head>
        <body>
           <nav></nav>
           <div th:replace="this :: html[!class]/body"/>
        </body>
    </html>
    

    更新我得到了开发者的回复https://github.com/thymeleaf/thymeleaf/issues/626

    Thymeleaf 使用基于拉取或基于片段包含的布局架构或默认情况下。

    Layout Dialect 可以使用分层布局样式,最好这样做。

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2020-11-12
      相关资源
      最近更新 更多