Velocity是什么?一个java的后端模板引擎,后缀名是.vm
常用指令:
"#"用来标识Velocity的脚本语句,包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等;
如:
#if($info.imgs)
<img src="$info.imgs" border=0>
#else
<img src="noPhoto.jpg">
#end
#if($foo<10)
<strong>Go North</strong>
#elseif($foo==10)
<strong>Go East</strong>
#elseif($bar==6)
<strong>Go South</strong>
#else
<strong>Go West</strong>
#end
$"用来标识一个对象(或理解为变量);
如:$i、$msg、$TagUtil.options(...)等
"!"用来强制把不存在的变量显示为空白。
如当页面中包含$msg,如果msg对象有值,将显示msg的值,如果不存在msg对象同,则在页面中将显示$msg字符。这是我们不希望的,为了把不存在的变量或变量值为null的对象显示为空白,则只需要在变量名前加一个“!”号即可。
当使用!时表示当此变量值为空时,显示空字符串。比如当$article为空,那会显示“$article“,而$!article会显示为“”
如:$!Msg
在模板中设置变量:#set( $a = "Velocity" )
变量和字符串如何拼接: 例: <span>${obj.name}我是大晴</span>
对象调用方法: 例如:$article.GetListByTitle('nvelocity')或${article.GetListByTitle('nvelocity')}。其实对对象的属性值也可以用$article.get_Title()获得。
循环语法:
#foreach( $info in $list) $info.someList #end 循环读取集合list中的对象,并作相应的处理。
如:EasyJF开源论坛系统中论(0.3)坛首页显示热门主题的html界面模板脚本:
#foreach( $info in $hotList1)
<a href="/bbsdoc.ejf?easyJWebCommand=show&&cid=$!info.cid" target="_blank">$!info.title</a><br>
#end
上面的脚本表示循环遍历hotList1集合中的对象,并输出对象的相关内容。
首先是#foreach的简单示例:
#foreach( $elem in $allElems)
$elem</br>
#end
上面这个例子中,$allElems可以是一个Vector,一个HashTable,一个数组。
在Velocity中,有一个变量$velocityCount用作循环计数,初始值是1。这个变量的名字和初始值是在velocity.properties文件里配置的。
$velocityCount
这个变量在velocity属性文件中定义,在#foreach的时候可以用得上,比如我foreach一个List<User>时,我们可以使用$velocityCount判断完成形如“张三,李四”的输出(李四后面没有逗号)
Java代码
1. #foreach($user in $users)
2. #userNode($user)#if($velocityCount != $user.size()),#end
3. #end
或
Java代码
1. #foreach($user in $users)
2. #if($velocityCount != 1),#end #userNode($user)
3. #end
默认$velocityCount 从1开始。
#Parse
#Parse用来在当前模板中引入并执行另一个(本地的)模板——可以是静态的,也可以是动态的——并把结果嵌入到当前位置。#Parse()指令的参数,可以是一个双引号括起来的文件名,也可以是一个变量,但是它不能接受多个参数。
被#Parse引入的文件仍然可以使用#Parse指令。在velocity.properties文件中有一个属性directive.parse.max.depth,默认值是10,它指定了#Parse嵌套的最大层次。既然#Parse嵌套是允许的,#Parse递归也是允许的。
假如a.vm #Parse b.vm,那么a.vm中定义的变量v,在b.vm中可以随便使用。如果b.vm也定义了v,在b.vm中可以随便使用。如果b.vm也定义了v,那么b.vm中用到的将会是自己的v,而不是a.vm中的v,而不是a.vm中的v。
包含文件#inclue("模板文件名")或#parse("模板文件名")
主要用于处理具有相同内容的页面,比如每个网站的顶部或尾部内容。
使用方法,可以参考EasyJF开源Blog及EasyJF开源论坛中的应用!
如:#parse("/blog/top.html")或#include("/blog/top.html")
parse与include的区别在于,若包含的文件中有Velocity脚本标签,将会进一步解析,而include将原样显示。
注释:
velocity的注释是用多个#号来标识的,大段注释用 #* 和 *#包起来
单行注释:##注释内容
多行注释:
#*
注释内容
*#
宏调用
macro指令让模板设计者可以将些重复、相关的的脚本版断定义为一个功能块.
这是一个独立的vm模板
a.vm内容片段
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
在b.vm中调用
b.vm中的内容片段
1.引入a.vm
2.
#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )
<table>
#tablerows( $color $greatlakes )
</table>
输出结果:
<table>
<tr><td bgcolor="blue">Superior</td></tr>
<tr><td bgcolor="blue">Michigan</td></tr>
<tr><td bgcolor="blue">Huron</td></tr>
<tr><td bgcolor="blue">Erie</td></tr>
<tr><td bgcolor="blue">Ontario</td></tr>
</table>
如果将宏#tablerows($color $list) 定义到一个模板库中(Velocimacros template library), 其它模板就都可以访问它了.
尽量不要直接在模板中使用#parse() 包含#macro() 指令.因为#parse() 动作在运行时执行,时会有一个在VM 中查找元素的过程.
在js中调用的例子:
参考学习地址:
https://www.cnblogs.com/yuepeng/archive/2010/11/23/1885524.html
<!DOCTYPE html>
<html lang="UTF-8">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="${json.staticIP}/css/weui.min.css">
<link rel="stylesheet" href="${json.staticIP}/css/jquery-weui.css">
<link rel="stylesheet" href="${json.staticIP}/css/intelligent/alreadyPropertyDeliveryPage.css?v=9">
<title>物业交割</title>
<style>
</style>
</head>
<body >
<div class="readings none">
<p class="choice-p">水电表初始读数还未录入系统,请设置物业交割时各表起始读数</p>
<div class="weui-cells">
<div class="weui-cell">
<div class="weui-cell__hd">
<p>电表初始读数</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="" readonly>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd">
<p>水表初始读数</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="" readonly>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd">
<p>热水表初始读数</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="" readonly>
</div>
</div>
</div>
<input type="button" value="设置" class="btn_ann" id="btn">
</div>
<div class="noreading top none">
<div class="weui-cells">
<div class="weui-cell">
<div class="weui-cell__hd">
<p>交割日期</p>
</div>
<div class="weui-cell__bd">
<input id="getDeliverAt" class="weui-input" type="text" value="" readonly>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd">
<p>操作人</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="${json.getDeliverBy}" readonly>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd">
<p>电表读数</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="${json.getElectricStartDegree}" readonly>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd">
<p>水表读数</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="${json.getWaterStartDegree}" readonly>
</div>
</div>
<div class="weui-cell" id="getHotWaterStartDegreeDiv">
<div class="weui-cell__hd">
<p>热水表读数</p>
</div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="${json.getHotWaterStartDegree}" readonly>
</div>
</div>
</div>
<input type="button" value="返回" class="btn_ann" id="btn2">
</div>
<script src="${json.staticIP}/js/jquery-1.12.3.min.js?v=3233"></script>
<script src="${json.staticIP}/js/fastclick.js"></script>
<script src="${json.staticIP}/js/jquery-weui.min.js?v=2" charset="utf-8"></script>
<script src="${json.staticIP}/js/isLoginNew.js?v=3233"></script>
<script>
var path = "${json.ctx}";
var staticIP = "${json.staticIP}";
var isAlreadyPropertyDelivery = "${json.isAlreadyPropertyDelivery}";
var houseId = "${json.houseId}";
var getDeliverAt = "${json.getDeliverAt}";
getDeliverAt = getDeliverAt.split(' ')[0];
$('#getDeliverAt').val(getDeliverAt);
if(isAlreadyPropertyDelivery=="true"){
if("${json.getHotWaterStartDegree}"==""){
$("#getHotWaterStartDegreeDiv").hide();
}
$(".noreading").show();
}else{
$(".readings").show();
}
$("#btn").click(function(){
window.location.href=path+'/intelligent/setAlreadyPropertyDeliveryPage?houseId='+houseId;
})
$("#btn2").click(function(){
history.go(-1);
})
$(function() {
FastClick.attach(document.body);
});
</script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
var url = window.location.href;
var articleId = "";
var shareTitle="给新兴品质人群一个有温度的智能家";
var shareImgUrl="${json.staticIP}/img/flag.jpg";
var userinfo = localStorage.getItem("_userinfo");
var timestamp;
var noncestr;
var signature;
//获取签名
$.ajax({
type: "GET",
url: "/corpservice/staff/user/getJsapiSigna",
//data:{timestamp:timestamp,noncestr:noncestr,url:url},
data:{url:url},
dataType : "json",
success: function(data){
timestamp=data.data.timestamp;
noncestr=data.data.nonceStr;
signature=data.data.signature;
console.log(data.data.timestamp);
wxShare();
}
});
function wxShare(){
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: 'wx1339193604579fe0', // 和获取Ticke的必须一样------必填,公众号的唯一标识
timestamp:timestamp, // 必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature: signature,// 必填,签名,见附录1
jsApiList: [
'onMenuShareAppMessage','onMenuShareTimeline','onMenuShareQQ','onMenuShareQZone','showMenuItems','hideMenuItems',
'uploadImage','previewImage','chooseImage'
] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
wx.ready(function(){
//config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,
//config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关
//接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
//----------“分享给朋友”
wx.onMenuShareAppMessage({
title: "龙湖冠寓官方网站", // 分享标题
desc: shareTitle, // 分享描述
link: "http://guanyu.longfor.com/html/h5/index.html", // 分享链接
imgUrl: shareImgUrl, // 分享图标
type: '', // 分享类型,music、video或link,不填默认为link
dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
success: function () {
// 用户确认分享后执行的回调函数、
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//------------"分享到朋友圈"
wx.onMenuShareTimeline({
title: '给新兴品质人群一个有温度的智能家', // 分享标题
link: "http://guanyu.longfor.com/html/h5/index.html", // 分享链接
imgUrl: shareImgUrl, // 分享图标
success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//-------------分享到QQ
wx.onMenuShareQQ({
title: '龙湖冠寓官方网站', // 分享标题
desc: shareTitle, // 分享描述
link: "http://guanyu.longfor.com/html/h5/index.html", // 分享链接
imgUrl: shareImgUrl, // 分享图标
success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//-------------分享到QQ空间
wx.onMenuShareQZone({
title: '龙湖冠寓官方网站', // 分享标题
desc: shareTitle, // 分享描述
link: "http://guanyu.longfor.com/html/h5/index.html", // 分享链接
imgUrl: shareImgUrl, // 分享图标
success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
wx.hideMenuItems({
menuList: ["menuItem:share:appMessage", "menuItem:share:timeline", "menuItem:share:qq","menuItem:share:weiboApp","menuItem:favorite", "menuItem:share:facebook","menuItem:copyUrl", "menuItem:openWithQQBrowser", "menuItem:openWithSafari","menuItem:readMode","menuItem:share:QZone","menuItem:share:brand"] // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3
});
$("#xiaopiao").click(function(){
wxChooseImage(1);
})
});
//拍照或从手机相册中选图接口
function wxChooseImage(type) {
wx.chooseImage({
count: 1,
needResult: 1,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (data) {
localIds = data.localIds[0].toString(); // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
//if (rh.tostr(localIds)) {
wxuploadImage(localIds,type);
//}
},
fail: function (res) {
alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", "");
}
});
}
//上传图片接口
function wxuploadImage(e,type) {
wx.uploadImage({
localId: e, // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
mediaId = res.serverId; // 返回图片的服务器端ID
if(type==1){
$("#xiaopiao").attr("src",localIds);
$("#xiaopiao").attr("mediaId",mediaId);
//var div = '<img src="'+localIds+'" mediaId = "'+mediaId+'" class="shangchuan" name="pic"/>'
//$("#upload").prepend(div);
}else if(type==2){
}else if(type==3){
}else if(type==4){
}else{
}
},
fail: function (error) {
picPath = '';
localIds = '';
alert(Json.stringify(error));
}
});
}
</script>
</body>
</html>