当前位置:网站首页>Velocity syntax

Velocity syntax

2022-06-22 19:44:00 ying1979

The second is a corresponding Java program called HelloWorld.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
2
3
4
5
6
7
8
  $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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
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
2
3
4
5
6
7
8
9
10
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
2
3
4
5
6
7
8
9
10
11
    #set()
    #if()
    #else
    #elseif()
    #end
    #foreach()
    #include()
    #parse()
    #macro()
 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
     #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
2
3
4
5
6
7
8
9
10
  #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
2
3
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

http://kino.blog.chinajavaworld.com/entry/3607/0/

原网站

版权声明
本文为[ying1979]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221822087071.html