velocity简单学习中

 velocity模板语法的javascript实现,Velocity是基于Java的模板引擎,应用广泛。Velocity模板适用于大量模板使用的场景,支持模板嵌套,复杂的逻辑运算,包含基本数据类型、变量赋值和函数等功能。
{%widget name="vm" data='{"name":"myname"}'%}
注意data之间的单双引号,data内容必须为json类型
data传参数据源,如 {%widget name="vm" data='{"name":"myname"}' %} 中的{"name":"myname"}
数据源文件,如widget/vm/vm.json的内容
两者优先级 "data传参数据源" > "数据源文件",即data传参数据源和数据源文件,数据名称相同时,以"data传参数据源"为准
1."#"用来标识Velocity的脚本语句,包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等,如:


#if($info.images)
<img src="$info.images">
#else
<img src="noPhoto.jpg">
#end
2."$"用来标识一个变量,如


$i、$msg.errorNum
3."!"用来强制把不存在的变量显示为空白


$!msg
4.注释,如:


## 这是一行注释,不会输出




<html>
<body>
<pre>
Hello VM.


## 注释


#*
注释
*#


value1:$!{value1}
$!{value2}
${value3}
---Print:value1:vv1


#foreach ($color in $colors)
Color $!{foreach.index}/$!{foreach.count}: $!{color}
#end
---Print: Color 0/1 :RED
Color 1/2 :GREEN
Color 2/3 :BLUE


#foreach($key in $map.keySet())
Number $!{foreach.index}/$!{foreach.count}: $!{key} $map.get($key)
#end
---Print: Number 0/1:0 0
Number 1/2:1 1
Number 2/3:2 4
Number 3/4:3 9


#*
通过entrySet方法遍历到的是Map中的每个实体(都是K-V的键值对)
*#
#foreach($kv in $map.entrySet())
Number $!{foreach.index}/$!{foreach.count}: $!{kv.key} $!{kv.value}
#end
---Print: Number 0/1:0 0
Number 1/2:1 1
Number 2/3:2 4
Number 3/4:3 9


User:$!{user.name}##会自动去查找是否存在getName之类的方法
#*
第二种方式是调用User类中属性对应的get方法
*#
User:$!{user.getName()}
---Print: User:Megustas
User:Megustas


#set($title = "megustas")
##公共部分尽量避免重复,因此公共部分用一个文件分离出来,方便每次调用
#*
include纯粹的将文本包含进来
*#
Include: #include("header.vm") <br>
#*
---Print:Include:Title $!title


parse不仅将文本包含进来,并且对这段文本进行一个编译和转化,因此header.vm文件中的title属性值变成了megustas
*#
Parse:#parse("header.vm")


---Print: Parse:Title megustas


##定义函数render_color
#macro (render_color, $color, $index)
Color By Macro $index, $color
#end


#foreach ($color in $colors)
    #render_color($color, $foreach.index)
#end


---Print:Color By Macro 0,RED
Color By Macro 1,GREEN
Color By Macro 2,BLUE


##定义变量set
#set($hello = "hello")
##使用双引号""才会对文本内容进行解释,''单引号仍保持文本状态
#set($hworld1 = "$!{hello} world")
#set($hworld2 = '$!{hello} world')


hworld1:$hworld1
hworld2:$hworld2


---Print: hworld1:hello world 
hworld2:$!{hello}world


$!{colors.size()}


---Pring : 3


</pre>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_21325705/article/details/80350515