当前位置:网站首页>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
边栏推荐
猜你喜欢

ActiveReports报表实战应用教程(十九)——多数据源绑定

Shell script explanation (VII) -- regular expression, sort, uniq, tr

Interface development component devaxpress asp Net core v21.2 - UI component enhancements

【干货|接口测试必备技能-常见接口协议解析】

第一章 力扣热题100道(1-5)
![[dry goods | necessary skills for interface testing common interface protocol analysis]](/img/6f/752078d6aac782c48c13c5d04ac525.png)
[dry goods | necessary skills for interface testing common interface protocol analysis]

数字赋能机械制造业,供应链协同管理系统解决方案助力企业供应链再升级

1.3-----Simplify 3D切片软件简单设置

Adapter mode of structural mode

实验4 NoSQL和关系数据库的操作比较
随机推荐
ABAQUS 使用RSG绘制插件初体验
Intelligent procurement system solution for processing and manufacturing industry: help enterprises realize integrated and Collaborative Procurement in the whole process
Longest common subsequence
K8s deploy MySQL
shell脚本(五)——函数
结构型模式之代理模式
calendar控件编程
Flutter系列-Dart基础语法学习
下拉刷新及上拉加载更多的ListView
Explain in simple terms the bloom filter
常用技术注解
Digital supply chain centralized purchase platform solution for mechanical equipment industry: optimize resource allocation and realize cost reduction and efficiency increase
84. (cesium chapter) movement of cesium model on terrain
SSH password free login
给对象赋值
Notes on Combinatorics (V) chains in distributive lattice
antd tree 树状选择器 子类必填
0.1-----用AD画PCB的流程
Cluster, distributed and microservice concepts and differences
Error in created hook: “TypeError: Cannot read property ‘tableId‘ of undefined“