是否有可能在Thymeleaf中创建动态替换?
我有以下控制器:
@Controller
public class LoginController {
@RequestMapping("/login")
public String getLogin(Model model){
model.addAttribute("template","login");
return "index";
}
}
Run Code Online (Sandbox Code Playgroud)
以下观点:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head></head>
<body>
<div th:replace="fragments/${template} :: ${template}"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Error resolving template "fragments/${template}", template might not exist or might not be accessible by any of the configured Template Resolvers
Run Code Online (Sandbox Code Playgroud)
UPDATE
我试图像这样预处理我的变量:
<div th:replace="fragments/${__#{${template}}__} :: ${__#{${template}}__}"></div>
Run Code Online (Sandbox Code Playgroud)
现在${template}如何取代login我现在有以下错误:
Exception evaluating SpringEL expression: "??login_en_US??"
Run Code Online (Sandbox Code Playgroud)
Wer*_*erb 12
虽然Joe Essey的解决方案也正常运行,但我解决了以下代码:
<div th:replace="@{'fragments/' + ${template}} :: ${template}"></div>
Run Code Online (Sandbox Code Playgroud)
我相信在百里香中管理这种行为的适当方法是使用layout:fragment标签。如果我错了,请纠正我。这是我的布局页面的一个简单示例,以及“动态”加载的登录页面:
布局.html
<html xmlns:layout="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
</head>
<body>
<div>
<div class="app-container">
<div th:fragment="content">
</div>
</div>
</div>
<div th:fragment="script"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
然后,当登录加载时,它会将th:fragmentdiv 替换为 html 视图中与控制器方法返回的字符串相匹配的关联 div,在本例中为 login.html:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.w3.org/1999/xhtml"
layout:decorator="layout">
<head>
<title>Login</title>
</head>
<body>
<div th:fragment="content">
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
现在,如果您想有条件地加载另一个片段,我采取的方法是添加带有 th:if 情况的替换标签。以下是根据当前用户的属性显示不同问题的表单示例:
<div th:if="${foo.type)} == 'type_1'">
<div th:replace="fragments/custom-questions :: type-1-checkboxes"></div>
</div>
<div th:if="${foo.type} == 'type_2'">
<div th:replace="fragments/custom-questions :: type-2-checkboxes"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
然后从文件 custom-questions.html 加载关联的 div:
<div th:fragment="type-1-checkboxes">
//stuff
</div>
<div th:fragment="type-2-checkboxes">
//stuff
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14429 次 |
| 最近记录: |