可以使用Thymeleaf的条件表达式来实现根据引用页面不同作不同变化。
假设有两个页面:page1.html和page2.html,它们都引用了同一个模板template.html中的一个元素。
在template.html中,可以使用Thymeleaf的条件表达式来判断当前引用页面的名称,从而作出不同的变化。示例代码如下:
```html
<div th:replace="fragments/myFragment :: myElement">
<p th:if="${#httpServletRequest.getRequestURI() == '/page1.html'}">This is page 1</p>
<p th:if="${#httpServletRequest.getRequestURI() == '/page2.html'}">This is page 2</p>
</div>
```
在上面的代码中,使用了Thymeleaf的内置变量#httpServletRequest来获取当前请求的URI,然后使用条件表达式来判断当前引用页面的名称,从而在myElement元素中显示不同的内容。
需要注意的是,如果模板中使用了Thymeleaf的缓存机制,那么可能会导致条件表达式不生效。为了避免这种情况,可以在模板中添加th:fragment属性,以使Thymeleaf不缓存该元素。示例代码如下:
```html
<div th:fragment="myElement">
<p th:if="${#httpServletRequest.getRequestURI() == '/page1.html'}">This is page 1</p>
<p th:if="${#httpServletRequest.getRequestURI() == '/page2.html'}">This is page 2</p>
</div>
```
在Thymeleaf中,可以使用`th:if`和`th:unless`来实现条件判断。如果需要在条件不成立时执行其他操作,可以使用`th:if`和`th:unless`的else语句。
示例如下:
```html
<div th:replace="fragments/myFragment :: myElement">
<p th:if="${#httpServletRequest.getRequestURI() == '/page1.html'}">This is page 1</p>
<p th:unless="${#httpServletRequest.getRequestURI() == '/page1.html'}">This is not page 1</p>
</div>
```
在上面的示例中,如果当前请求的URI是`/page1.html`,则会显示`This is page 1`;否则会显示`This is not page 1`。
如果要在`th:if`和`th:unless`的条件不成立时执行其他操作,可以使用`th:if`和`th:unless`的else语句。示例代码如下:
```html
<div th:replace="fragments/myFragment :: myElement">
<p th:if="${#httpServletRequest.getRequestURI() == '/page1.html'}">This is page 1</p>
<p th:unless="${#httpServletRequest.getRequestURI() == '/page1.html'}">This is not page 1</p>
<p th:else>Unknown page</p>
</div>
```
在上面的示例中,如果当前请求的URI是`/page1.html`,则会显示`This is page 1`;否则会显示`This is not page 1`;如果请求的URI既不是`/page1.html`,也不是其他已知的URI,就会显示`Unknown page`。