Thymealeaf模板引擎入门 这个案例非常底层的操作 :

静态渲染

(1)创建测试工程,引入依赖

(1)创建测试工程,引入依赖

<dependency>

    <groupId>org.thymeleaf</groupId>

    <artifactId>thymeleaf</artifactId>

    <version>3.0.11.RELEASE</version>

</dependency>

 

 会带入导入 thymeleaf的jar包

<dependency>

    <groupId>org.thymeleaf</groupId>

    <artifactId>thymeleaf-spring5</artifactId>

    <version>3.0.11.RELEASE</version>

</dependency>

 

2 静态渲染(生成HTML文件)  

编写模板

<!DOCTYPE html>

<html xmlns="http://www.thymeleaf.org"> //固定格式.价格标签xmlns

//<div>内的内容是需要用name这个变量替换的,即使div有内容也会被替换掉    

<div th:text="${name}">div的内容</div>   

 

 

3 编写JAVA代码

 public static void main(String[] args) {

        // 1.上下文,承载数据模型:就是我们模板页面需要的变量的值

        Context context = new Context();

        //创建数据模型

        Map<String, Object> dataModel = new HashMap();

        //变量name  ,,可以加很多变量  //接收传回去的数据"<h1>青橙电商系统</h1>,也可以是变量如skuList

        dataModel.put("nameList", nameList);   //把nameList数据装到数据模型中

        dataModel.put("context", "<h3>页面中的内容</h3>"); //<h3>页面中的内容</h3>这个字符串装到context中

        context.setVariables(dataModel);//数据模型设置到上下文里

        

        

      <!-- 把目标文件写到配置文件中

       @Value("${pagePath}")

        private  String pagePath; 

     File dest = new File(pagePath);

        -->

        // 2.准备文件:最终要输出的目标文件,实际部署是在linux环境中,路径不能写死.

        File dest = new File("D:\\temp\\thymeleaf\\test_out.html");//生成的页面写的文件位置

        

        // 3.生成页面

        try {

            //用文件实例化一个PrintWriter对象

            PrintWriter writer = new PrintWriter(dest, "UTF-8");

            //创建模板解析器,可以在配置里面配置

        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();

            resolver.setTemplateMode(TemplateMode.HTML);//模板模型:指定模板类型是html

           // resolver.setSuffix(".html");//设置后缀,执行模板引擎就不要加后缀html了

        

            //使用模板引擎就可以生成页面

            TemplateEngine engine = new TemplateEngine();//创建模板引擎

            engine.setTemplateResolver(resolver);//设置模板解析器

                        // 模板名称,     上下文, 文件的实例化对象

            engine.process("test.html", context, writer);//执行模板引擎,根据test.html模板生成页面,context上下文,writer是PrintWriter对象

        

        } catch (Exception e) {

            e.printStackTrace();

        }}

猜你喜欢

转载自www.cnblogs.com/hudahui/p/11645027.html