springboot&mustache
引
言
mustache官方给出的是Logic-less templates.翻译过来就是逻辑很少的模板,Mustcache可以被用于html文件,配置文件,源代码等等很多场景,它的运行得益于扩展一些标签在模板文件中,然后使用一个hash字典或者对象对其进行替换渲染。我们之所以称之为“logic-less”是因为他摒弃了if else 以及for loop 这样的语句,取而代之的是只有标签,有些标签被替换成一个值,或者不作为,或者是一系列的值,比如数组或者一个列表,标签有几种不同的类型,自接下来我们会逐个介绍,但是你要相信他非常简单,因为他是“logic-less”的。
此篇我们讲述一下springboot如何整合mustache。
一
目标
基于springboot2.x,整合mustache模板引擎,并展示用户的基本信息。
二
springboot整合mustache
1:引入依赖
springboot整合mustache除了引入基础依赖之外,还要引入spring-boot-starter-mustache。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mustache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mustache</artifactId> </dependency>
springboot将引入所有必须的依赖并且注入所有必需的配置来使用mustache。
2:编码实现
用户信息实体类:
@Setter @Getter @ToString public class User implements Serializable { private Long id; // 主键ID private String name; // 姓名 private Date createTime; private Integer sex; private Integer age; }
编写IndexController处理简单的用户信息查询请求:
@Controller @Slf4j public class IndexController { @GetMapping("/user") public String queryUser( Model model) { User user = new User(); user.setId(10086L); user.setName("Typhoon"); user.setAge(28); model.addAttribute("user",user); return "/index"; } }
在src/main/resources目录下新建templates文件夹并新建index.mustache文件:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>用户信息</h2> <div> <p>ID:{{user.id}} <p>名字:{{user.name}}</p> <p>年龄:{{user.age}}</p> </div> </body> </html>
编写应用启动类:
@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
3:启动应用&测试
启动应用,浏览器输入http://localhost:8080/user:
总结
mustache是一种更轻量级的模板引擎,其放弃了一些复杂的语法,使用标签来实现更便捷的开发,相对于Thymeleaf和freemarker更加易用,在一些简单的应用中使用mustache也是不错的选择。
本文分享自 PersistentCoder 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!