前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot(17)-mustache

springboot(17)-mustache

作者头像
叔牙
发布2020-11-19 15:18:06
1.1K0
发布2020-11-19 15:18:06
举报
文章被收录于专栏:一个执拗的后端搬砖工

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也是不错的选择。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-11-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 PersistentCoder 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档