Nav*_*tor 0 spring thymeleaf spring-boot
我有一个创建模型属性并传递给视图“partial.html”以生成输出的控制器
部分.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home page</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<p>
<span th:text="'Today is: ' + ${message}"></span>
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
并在控制器方法中
model.addAttribute("message", search);
Run Code Online (Sandbox Code Playgroud)
如何将 Htlm 输出到控制器方法中的字符串?像这样
String htmlOutput="from partial.html";
Run Code Online (Sandbox Code Playgroud)
小智 6
假设您有一个 HTML 文件,其中包含两个变量name和todayDate.
您想处理它并将其存储在字符串/数据库/AWS S3 中。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hello</p>
<p th:text="${name}"></p>
<p th:text="${todayDate}"></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您的 HTML 文件位置是 src/main/resources/templates/home.html
通过使用以下函数,您可以获得最终处理的 HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hello</p>
<p>Manoj</p>
<p>30 November 2019</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
import org.thymeleaf.context.Context;
@GetMapping("/")
public void process() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setCacheable(false);
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
// https://github.com/thymeleaf/thymeleaf/issues/606
templateResolver.setForceTemplateMode(true);
templateEngine.setTemplateResolver(templateResolver);
Context ctx = new Context();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
Calendar cal = Calendar.getInstance();
ctx.setVariable("todayDate", dateFormat.format(cal.getTime()));
ctx.setVariable("name", "Manoj");
final String result = templateEngine.process("home", ctx);
System.out.println("result:" + result);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3601 次 |
| 最近记录: |