velocity

Velocity是一个基于Java的模板引擎,其提供了一个Context容器,在java代码里面我们可以往容器中存值,然后在vm文件中使用特定的语法获取,这是velocity基本的用法,其与jsp、freemarker并称为三大视图展现技术,相对于jsp而言,velocity对前后端的分离更加彻底:在vm文件中不允许出现java代码,而jsp文件中却可以.

作为一个模块引擎,除了作为前后端分离的MVC展现层,Velocity还有一些其他用途,比如源代码生成、自动email和转换xml等,具体的用法可以参考这篇文章


基础语法

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

##  使用$vari获取变量时,如果变量不存在,Velocity引擎会将其原样输出,通过使用\$!{}的形式可以将不存在的变量变成空白输出.

    $!{value1}
    $!{value2}
    ${value3}

##  $!{foreach.count}记录当前循环次数的计数器,默认从1开始计数

    #foreach($color in $colors)
        Color $!{foreach.index}/$!{foreach.count}: $!{color}
    #end

    #foreach($key in $map.keySet())
        Number $!{foreach.index}/$!{foreach.count}: $!{key} $map.get($!{key})
    #end

    #foreach($kv in $map.entrySet())
        Number $!{foreach.index}/$!{foreach.count}: $!{kv.key} $!{kv.value}
    #end

    User:$!{user.name}
    User:$!{user.getName()}

##    定义变量
    #set($title = "coder")
##    纯文本扩展
    Include: #include("header.vm") <br>
##    变量解析
    Parse:#parse("header.vm")

##    在Velocity中也有宏的概念,可以将其作为函数来理解,使用#macro声明宏
    #macro (render_color $color, $index)
        Color By Macro $index, $color
    #end

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

    #set($hello = "hello")
    #set($hworld1 = "$!{hello} world")
    #set($hworld2 = '$!{hello} world')

    $!{colors.size()}

    hworld1:$hworld1
    hworld2:$hworld2
</pre>
</body>
</html>
  • velocity中变量是弱类型的。
  • ${name} ,也可以写成:$name。提倡用前面的写法。
  • 在Velocity中可以通过parse或者include指令引入外部vm文件,但是二者存在区别:include指令会将外部文件原样输出,而parse指令会先对其进行解析再输出(即对外部文件中的vm语法解析)。
  • 详细语法参见这里

velocity、freemarker 、JSP


Springboot使用velocity模板引擎

Springboot使用velocity模板引擎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值