8.3 弹性布局:超越片段插入

多亏了分段表达式,我们可以给片段指定文本、数字、bean对象之外的参数——标记的片段。

这允许我们以这样一种方式创建模版:正在调用中的模版可以对它们进行补充,从而形成了一种非常具有弹性的模版布局机制

注意titlelinks变量在以下片段中的使用:

  1. <head th:fragment="common_header(title,links)">
  2. <title th:replace="${title}">The awesome application</title>
  3. <!-- Common styles and scripts -->
  4. <link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
  5. <link rel="shortcut icon" th:href="@{/images/favicon.ico}">
  6. <script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>
  7. <!--/* Per-page placeholder for additional links */-->
  8. <th:block th:replace="${links}" />
  9. </head>

我们现在可以像这样调用片段:

  1. ...
  2. <head th:replace="base :: common_header(~{::title},~{::link})">
  3. <title>Awesome - Main</title>
  4. <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
  5. <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
  6. </head>
  7. ...

结果会使用正在调用中的模版里的实际的<title><link>标签,把它们作为titlelinks变量的值,使我们的模版在插入的时候被自定义:

  1. ...
  2. <head>
  3. <title>Awesome - Main</title>
  4. <!-- Common styles and scripts -->
  5. <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  6. <link rel="shortcut icon" href="/awe/images/favicon.ico">
  7. <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script>
  8. <link rel="stylesheet" href="/awe/css/bootstrap.min.css">
  9. <link rel="stylesheet" href="/awe/themes/smoothness/jquery-ui.css">
  10. </head>
  11. ...