vm(velocity)模板变量定义及使用

本文详细介绍了如何在Velocity模板引擎中设置和使用变量,包括在VelocityUtils.java中定义方法prepareContext来准备上下文变量,以及如何在模板中通过#set指令获取和使用这些变量。

定义变量写到VM模板中
在VelocityUtils.java 文件中写
该文件中定义方法:
public static VelocityContext prepareContext(GenTable genTable)
定义变量
VelocityContext velocityContext = new VelocityContext();[到时候返回这个变量]
在该文件中设置变量
velocityContext.put(“tplCategory”, genTable.getTplCategory());
velocityContext.put(“tableName”, genTable.getTableName());

在setTreeVelocityContext这个方法[该方法为设置树在模板中的变量]
例:
context.put(“treeCode”, treeCode);
context.put(“treeParentCode”, treeParentCode);
context.put(“treeName”, treeName);
context.put(“expandColumn”, getExpandColumn(genTable));
context.put(“orgLevel”,StringUtils.toCamelCase(“Org_Level”));
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE))

在模板中变量名即为context中Key
例:orgLevel
在VM中写法
#set(TreeLevel=TreeLevel=TreeLevel=orgLevel.substring(0,1).toUpperCase() + ${orgLevel.substring(1)})

通过获取外面context定义的值例:获取外面context定义的值 例:contextorgLevel[即获取外面定义的变量]
#set:设置值
KaTeX parse error: Expected 'EOF', got '#' at position 44: …值为orglevel截取的值 #̲set(TreeLevel=$orgLevel.substring(0,1).toUpperCase() + orgLevel.substring(1))使用:{orgLevel.substring(1)}) 使用:orgLevel.substring(1))使:{变量名}
例:
System.out.println("${TreeLevel}");
使用方法
// 初始化vm
VelocityInitializer.initVelocity();
// 设置vm中变量
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates)
{
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
// 将变量渲染到vm中
tpl.merge(context, sw);
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值