创建一个常规的web项目肯定需要一个模板引擎来实现,引用之前的项目《Vert.x 4 Web应用初识》基础结构
目前vert.x支持多款模板引擎,包括:
这里主要讲解一个Java编程熟悉的模板引擎Thymeleaf
maven pom.xml
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-templ-thymeleaf</artifactId>
<version>4.5.9</version>
</dependency>
这里模板引擎以Thymeleaf为例,编辑MainVerticle
代码聚焦
TemplateEngine templateEngine= ThymeleafTemplateEngine.create(vertx);
TemplateHandler templateHandler = TemplateHandler
.create(templateEngine);
// .create(templateEngine,"templates","text/html");
代码聚焦
//路径模板一对一映射
router.get("/about.html").handler(ctx->{
ctx.put("hello","hello world");
templateEngine.render(ctx.data(),"templates/about.html",bufferAsyncResult -> {
// 如果模板解析成功,就将结果写到response
if (bufferAsyncResult.succeeded()) {
ctx.response().putHeader("Content-Type", "text/html").end(bufferAsyncResult.result());
} else { // 如果解析失败,就显示fail
ctx.fail(bufferAsyncResult.cause());
}
});
});
<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>about</title>
</head>
<body>
<h1 th:text="${hello}"></h1>
<th:block th:insert="~{templates/common.html::desc}"></th:block>
</body>
</html>
<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="desc">
<p>
我是一段简单的介绍,每个页面都可以th:insert="~{common::desc}"引入哟
</p>
</th:block>
注意上方代码,暂未使用templateHandler
使用浏览器访问 http://localhost:8080/about.html
访问结果与预期一致。
不支持以下写法【红色提示】
router.get("/address.html").handler(ctx->{
ctx.put("hello","hello world");
ctx.next();
}).handler(templateHandler);
以上写法并不能将 /address.html 映射到 templates目录下address.html文件。
源码剖析
TemplateHandlerImpl实现类中调用了一个处理文件路径的方法
方法中有个坑,非正则匹配的这里会截取路径全部,导致上面的file拿到 “”空串然后 TemplateHandlerImpl 调用 模板引擎渲染时候路径拼接无法找到
上面一对一没用到TemplateHandler
TemplateHandler templateHandler = TemplateHandler
.create(templateEngine);
这里正则匹配多个会用到,下面为正则匹配对应路径开头的最后都要走模板解析器处理
//指定目录映射动态模板
router.get("/dynamic/*").last().handler(templateHandler);
//指定后缀映射动态模板
router.getWithRegex(".+\\.html").last().handler(templateHandler);
注意:必须加last()排序到最后,否则可能设定了参数因排序问题导致解析失败或报错。
对应目录使用路径参考代码
router.get("/product/detail.html").handler(ctx->{
ctx.put("hello","hello world");
ctx.next();
});
<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>product - detail</title>
</head>
<body>
<h1 th:text="${hello}"></h1>
<th:block th:insert="~{templates/common.html::desc}"></th:block>
</body>
</html>
上面是个.html
结尾的,受到上方第二个规则匹配,所以最后会渲染成对应的html,html模板位置为 templates/product/detail.html
(可以参考上面的源码剖析部分得到为啥是这个路径)
product/detail.html 模板存放位置参考
使用浏览器访问 http://localhost:8080/product/detail.html
从上图来看和我们预期结果一致。
至此我们学会了在Vert.x 4中使用模板引擎基础
http://blog.xqlee.com/article/2408131447063407.html