使用Velocity生成代码

Velocity前端语法

变量

$name 或  ${name}

定义变量  建议使用 ${name}  $name这种命名,有些命名类似的无法区分 如$name,$names

设置常量

#set($constant1="$")

注:因为$符号是Velocity的语法所以根据设置常量方式来赋值$

如果判断

#if($data==1)
#end

#if($data==1)

#elseif($data==2)

#else

#end

循环

循环List

#foreach($item in $data)
 计数:${velocityCount}  lable: ${item.lable}
end

循环Map

#foreach($item in $data.entrySet())  
${item.key}  ${item.value}  
#end

循环计数:

${velocityCount} 

判断是否循环最后一个

#if($foreach.hasNext)

#end

后端代码

public final class VelocityCommon {

    public static final VelocityCommon INSTANCE = new VelocityCommon();

    private static final String UTF8 = "UTF-8";

    private static final String CLASSPATH = "classpath";

    private static final String CLASSPATH_RESOURCE_LOADER_CLASS = "classpath.resource.loader.class";

    private static final String VELOCITY_CLASSPATH_RESOURCE_LOADER_CLASS = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader";

    static {
        INSTANCE.init();
    }

    /**
     * 初始化 Velocity
     * */
    private static void init() {
        Properties properties = new Properties();
        properties.setProperty(RuntimeConstants.INPUT_ENCODING, UTF8);
        properties.setProperty(RuntimeConstants.RESOURCE_LOADER, CLASSPATH);
        properties.setProperty(CLASSPATH_RESOURCE_LOADER_CLASS, VELOCITY_CLASSPATH_RESOURCE_LOADER_CLASS);
        Velocity.init(properties);
    }

    /**
     * 在Velocity生成模板
     */
    public final StringWriter getTemplate(String template, VelocityContext data) {
        Template tpl = Velocity.getTemplate(template, UTF8);
        StringWriter sw = new StringWriter();
        tpl.merge(data, sw);
        return sw;
    }


    /**
     * 在Velocity生成模板并导出
     */
    public final void writeTempleteToFile(String template, VelocityContext data, String fileName) throws IOException {
        StringWriter sw = getTemplate(template, data);
        IoUtils.writeStringToFile(new File(fileName), sw.toString(), UTF8);
    }

}

参考:https://www.cnblogs.com/Jimc/p/9789655.html

码云:youyue: 有岳,后台管理系统,springboot+mybatis+redis

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值