当前位置:网站首页>Velocity syntax
Velocity syntax
2022-06-22 19:44:00 【ying1979】
1 | import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class HelloWorld
{
public static void main( String[] args )
throws Exception
{
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();
/* next, get the Template */
Template t = ve.getTemplate( "helloworld.vm" );
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "World");
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
}
}
|
1 | Hello World! Welcome to Velocity! |
1 | $petList.size() Pets on Sale!
We are proud to offer these fine pets
at these amazing prices. This month only,
choose from:
#foreach( $pet in $petList )
$pet.name for only $pet.price
#end
Call Today!
|
1 | /* create our list of maps */
ArrayList list = new ArrayList();
Map map = new HashMap();
map.put("name", "horse");
map.put("price", "00.00");
list.add( map );
map = new HashMap();
map.put("name", "dog");
map.put("price", "9.99");
list.add( map );
map = new HashMap();
map.put("name", "bear");
map.put("price", ".99");
list.add( map );
/* add that list to a VelocityContext */
VelocityContext context = new VelocityContext();
context.put("petList", list);
|
1 |
import java.io.StringWriter;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class PetStoreEmail
{
public static void main( String[] args )
throws Exception
{
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();
/* organize our data */
ArrayList list = new ArrayList();
Map map = new HashMap();
map.put("name", "horse");
map.put("price", "00.00");
list.add( map );
map = new HashMap();
map.put("name", "dog");
map.put("price", "9.99");
list.add( map );
map = new HashMap();
map.put("name", "bear");
map.put("price", ".99");
list.add( map );
/* add that list to a VelocityContext */
VelocityContext context = new VelocityContext();
context.put("petList", list);
/* get the Template */
Template t = ve.getTemplate( "petstoreemail.vm" );
/* now render the template into a Writer */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* use the output in your email body */
sendEmail( writer.toString() );
}
}
|
1 | 3 Pets on Sale!
We are proud to offer these fine pets
at these amazing prices. This month only,
choose from:
horse for only 00.00
dog for only 9.99
bear for only .99
Call Today!
|
1 | #set()
#if()
#else
#elseif()
#end
#foreach()
#include()
#parse()
#macro()
|
1 | #set( $startrow = 0)
#set( $count = $current + 1 )
#set( $isReady = ( $isOn && $isOpen) )
#if( $value > 5 )
bigger
#elseif( $value < 5 )
smaller
#else
just right
#end
#foreach( $item in $itemList )
My $item.
#end
|
The collection types #foreach() supports are:
Object[]
java.util.Collection
java.util.Map (iterates over the mapped values)
java.util.Iterator
java.util.Enumeration
The #include() and #parse() directives are similar -- they both take a template or static resource name as an argument, include that template or resource in-place, and then render it to the output stream. The difference is that #include() includes the specified resource's content without any processing, and #parse() treats the specified resource as a template, processing all directives and references against the current context.
You can use these two directives to dynamically construct output. For example, in Web applications you can set up a skeleton for your pages, such as a set of top-level templates that may employ different navigational layouts or color/design schemes, and then #parse() and/or #include() the dynamic and static content elements at runtime based on user and application state:
| #parse( $header ) |
| #parse( $body ) |
| #parse( $footer ) |
Tips :velocity Medium case sensitive .
Velocity In particular, a method for obtaining the number of cycles is also provided ,$velocityCount The name of the variable is Velocity Default name .
Velocity Macros in can be understood as functions .
① Definition of macro
#macro( The name of the macro $ Parameters 1 $ Parameters 2 …)
Statement of body ( That's the body of the function )
#end
② Macro call
# The name of the macro ($ Parameters 1 $ Parameters 2 …)
explain : Space between parameters .
1 | #macro( select $name $displayname $choicelist )
<SELECT name=$name>
<option value="">$displayname</option>
#foreach( $choice in $choicelist )
<option value=$choice>$choice</option>
#end
</select>
#end
|
Then, anytime you need an HTML <select> widget, you could simply invoke the Velocimacro as a directive:
1 | Please choose: #select( "size" "--SIZE--" $sizelist ) |
VTL miscellany
I should mention a few other VTL features. VTL lets you create integers, string literals, Boolean values, arrays of objects, and arrays of sequential integers in the template:
#set( $myint = 5 )
#set( $mystring = 'Hello There')
#set( $mybool = true )
#set( $objarr = [ "a", $myint, $mystring, false ] )
#set( $intrangearr = [1..10] )
VTL also has an alternative string literal form, using double quotes (") that interpolates reference values (plus directives and Velocimacros):
#set( $foo = 'bar')
#set( $interp = "The value is '$foo'")
The resulting value of $interp is the string The value is 'bar'.
/n/n/n/n/n
#include and #parse The function of is to import local files , For safety reasons , Imported local files can only be imported in TEMPLATE_ROOT Under the table of contents .
difference :
(1) And #include The difference is ,#parse Only a single object can be specified . and #include There can be multiple
If you need to import multiple files , It can be separated by commas :
#include ("one.gif", "two.txt", "three.htm" )
In parentheses can be the file name , But more often, variables are used :
#include ( “greetings.txt”, $seasonalstock )
(2) #include The contents of the imported file will not be parsed by the template engine ;
and #parse The contents of the imported file Velocity The... Will be parsed velocity Syntax and hand it over to the template , That is to say, it is equivalent to the imported file copy To a file .
#parse It can be called recursively , for example : If dofoo.vm Include as follows :
Count down.
#set ($count = 8)
#parse ("parsefoo.vm")
All done with dofoo.vm!
So in parsefoo.vm In the template , You can include the following VTL:
$count
#set($count = $count - 1)
#if ( $count > 0 )
#parse( "parsefoo.vm" )
#else
All done with parsefoo.vm!
#end The display result is :
Count down.
8
7
6
5
4
3
2
1
0
All done with parsefoo.vm!
All done with dofoo.vm!
Be careful : stay vm Use in #parse To nest another vm Variable sharing problem in . Such as :
->a.vm Nesting inside b.vm;
->a.vm Variables are defined in $param;
->b.vm It can be used directly in $param, There is no limit .
But what needs special attention is , If b.vm Variables are also defined in $param, be b.vm Will use b.vm The value defined in
边栏推荐
- 51万奖池邀你参战!第二届阿里云ECS CloudBuild开发者大赛来袭
- shell脚本详解(十)——sed编辑器的使用方法
- ActiveReports报表实战应用教程(十九)——多数据源绑定
- Screw数据库文档生成器
- 【干货|接口测试必备技能-常见接口协议解析】
- About Random Forest
- [nfs无法挂载问题] mount.nfs: access denied by server while mounting localhost:/data/dev/mysql
- Methods for converting one-dimensional data (sequence) into two-dimensional data (image) GAFS, MTF, recurrence plot, STFT
- 数商云:解析B2B2C多用户商城系统架构设计思路,开启智能商城新时代
- SSH password free login
猜你喜欢

Experiment 7 trigger

Shell programming specification and variables

深入浅出聊布隆过滤器(Bloom Filter)

Wavelet transform DB4 for four layer decomposition and signal reconstruction matlab analysis and C language implementation

Altium Designer中off grid pin解决方法

小甲鱼老师《带你学C带你飞》的后续课程补充

Shell script (V) -- function

Message Oriented Middleware (I) MQ explanation and comparison of four MQS

Thread pool: reading the source code of threadpoolexcutor

shell脚本详解(十)——sed编辑器的使用方法
随机推荐
calendar控件编程
Teachers, I want to ask you a question. I run flinkcdc locally to synchronize MySQL data. The timestamp field parsing is normal,
结构型模式之代理模式
老师们,我想请教一个问题,我本地跑flinkcdc同步mysql数据timestamp字段解析正常,
84. (cesium chapter) movement of cesium model on terrain
取zip包中的文件名
Notes on Combinatorics (V) chains in distributive lattice
小波变换db4进行四层分解及其信号重构—matlab分析及C语言实现
vs2008 水晶报表升级到 vs2013对应版本
vim中快速缩进用法
3GPP 5g R17 standard is frozen, and redcap as an important feature deserves attention!
AttributeError: ‘KeyedVectors‘ object has no attribute ‘wv‘
Ts as const
5gc and satellite integrated communication scheme
Pat a 1093 count Pat's (25 points)
Common technical notes
Solution de pin hors grille dans altium designer
Shell编程规范与变量
Digital business cloud: build a digital supply chain system to enable enterprises to optimize and upgrade their logistics supply chain
ssh免密码登录