10.Velocity模版引擎

常见的应用场景:

  • Web内容生成 : 生成动态Web页面。
  • 代码生成 : 生成Java源代码、SQL脚本、XML配置文件等。
  • 网页静态化 : 生成静态网页。

index.html.vm

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>velocity快速入门</title>

</head>

<body>

<h3>心怀梦想,坚持不懈,成功即在前方。${message}</h3>

</body>

</html>

数据填充
编写java代码实现数据填充,并生成文件

package com.dkd.generator.util;

import java.util.Properties;
import org.apache.velocity.app.Velocity;
import com.dkd.common.constant.Constants;

/**
 * VelocityEngine工厂
 * 
 * @author ruoyi
 */
public class VelocityInitializer
{
    /**
     * 初始化vm方法
     */
    public static void initVelocity()
    {
        Properties p = new Properties();
        try
        {
            // 加载classpath目录下的vm文件
            p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // 定义字符集
            p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
            // 初始化Velocity引擎,指定配置Properties
            Velocity.init(p);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
}

package com.dkd.test;

import com.dkd.generator.util.VelocityInitializer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;

public class VelocityDemoTest {

    public static void main(String[] args) throws Exception {
        //1. 初始化模板引擎
        VelocityInitializer.initVelocity();
        //2. 准备数据模型
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("message", "加油朋友2!!");
        //3. 读取模板
        Template template = Velocity.getTemplate("vm/index.html.vm", "UTF-8");
        //4. 渲染模板 (文件保存至D:\\workspace\\index.html)
        FileWriter fileWriter = new FileWriter("D:\\workspace\\index.html");
        template.merge(velocityContext, fileWriter);
        fileWriter.close();
    }
}
image.png

image.png

基础语法
Velocity中的变量有两类

  • 在模板中定义变量: #set开头,比如 #set($name = "velocity")
  • 获取变量的的值: name 或者{name}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>velocity快速入门</title>

</head>

<body>

<h3>心怀梦想,坚持不懈,成功即在前方。${message}</h3>

## 定义变量
#set($name = "velocity")


## 输出变量
第一种情况:${name} <br>
第二种情况:$name <br>

## 第三种情况:orderService
#set($column = "order")
字符串拼接:${column}Service <br>


</body>

</html>

对象的定义获取

package com.dkd.test;

import com.dkd.common.annotation.Excel;
import com.dkd.common.core.domain.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 区域管理对象 tb_region
 *
 * @author itheima
 * @date 2024-06-05
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Region extends BaseEntity {
    private static final long serialVersionUID = 1L;

    /**
     * 主键ID
     */
    private Long id;

    /**
     * 区域名称
     */
    @Excel(name = "区域名称")
    private String regionName;

}

准备模型数据

package com.dkd.test;

import com.dkd.generator.util.VelocityInitializer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.util.List;

public class VelocityDemoTest {

    public static void main(String[] args) throws Exception {
        //1. 初始化模板引擎
        VelocityInitializer.initVelocity();
        //2. 准备数据模型
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("message", "加油朋友!!");
        // 创建区域对象
        Region region = new Region(1L, "北京北五环");
        velocityContext.put("region", region);

        //3. 读取模板
        Template template = Velocity.getTemplate("vm/index.html.vm", "UTF-8");
        //4. 渲染模板
        FileWriter fileWriter = new FileWriter("D:\\workspace\\index.html");
        template.merge(velocityContext, fileWriter);
        fileWriter.close();
    }
}
image.png

循环
循环的语法:#foreach(...) ... #end

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>velocity快速入门</title>

</head>

<body>

<h3>心怀梦想,坚持不懈,成功即在前方。${message}</h3>

    ## 定义变量
    #set($name = "velocity")


    ## 输出变量
第一种情况:${name} <br>
第二种情况:$name <br>

    ## 第三种情况:orderService
    #set($column = "order")
字符串拼接:${column}Service <br>

<hr>
    $region <br>
    ## 获取区域对象中的数据
区域ID:$region.id <br>
区域名称:${region.regionName} <br>
<hr>

    ##定义一个集合
    #set($list = ["春", "夏", "秋", "冬"])

    ## 遍历循环
    #foreach($item in $list)
    序号[$foreach.count] $item <br> ## count从1开始 index从0开始
    #end
<hr>

    ## 获取list集合中的数据
    $regionList <br>
    ## 遍历区域
    #foreach($item in $regionList)
    序号[$foreach.count],区域ID:$item.id,区域名称:$item.regionName <br>
    #end
</br>

</body>

</html>

准备模型数据

package com.dkd.test;

import com.dkd.generator.util.VelocityInitializer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.util.List;

public class VelocityDemoTest {

    public static void main(String[] args) throws Exception {
        //1. 初始化模板引擎
        VelocityInitializer.initVelocity();
        //2. 准备数据模型
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("message", "加油朋友2!!");
        // 创建区域对象
        Region region = new Region(1L, "上海");
        velocityContext.put("region", region);
        // 创建区域对象
        Region region1 = new Region(1L, "北京北五环");
        Region region2 = new Region(2L, "北京北四环");
        velocityContext.put("region", region1);
        List<Region> regionList = List.of(region1, region2);
        velocityContext.put("regionList", regionList);

        //3. 读取模板
        Template template = Velocity.getTemplate("vm/index.html.vm", "UTF-8");
        //4. 渲染模板
        FileWriter fileWriter = new FileWriter("D:\\workspace\\index.html");
        template.merge(velocityContext, fileWriter);
        fileWriter.close();
    }
}

if判断
判断的语法:#if(condition) ... #elseif(condition) ... #else ... #end

##定义变量
#set($score=80)

## if判断
#if($score>=80)
    优秀
#elseif($score>=60)
    及格
#else
    不及格
#end

## 对象obj不为空才会执行里面的逻辑
#if($obj) ..... #end

## 对象obj为空才会执行里面的逻辑
#if(!$obj) ..... #end
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容