使用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

码云:https://gitee.com/ausions/youyue

 

posted on 2022-07-28 18:10  ausions  阅读(203)  评论(0编辑  收藏  举报