Getting started with velocity scripts

Source: Internet
Author: User
Tags arithmetic operators
The following documents are collected from network I. Introduction to velocity

Velocity is an open-source product of Apache. It is a Java-based template engine that can flexibly combine background data objects with template files, when anyone is allowed to use the template language to reference the background Java code-Defined Object velocity for web development, the interface designer can develop a web site following the MVC Architecture in sync with Java program developers. That is to say, page designers can focus only on the page display effect, while Java developers focus on business logic encoding. Velocity separates Java code from web pages, which facilitates the long-term maintenance of web sites.

Velocity is a Java-based template engine that allows anyone to reference objects defined by Java code simply using the template language. As a relatively complete template engine, velocity has powerful functions, but it also increases application complexity.

Many people download the easyjweb open source application example. The purpose of easyjweb is to separate the page-program, that is, in a project, programmers use professional Java development tools (such as Eclipse and JBuilder) to compile, debug, and test programs. Page makers use professional web page creation tools (such as Macromedia Dreamweaver) to design and create webpages, the coordination between the two is solved through a standard interface protocol. Some tags need to be added to the page to generate dynamic content. This can be done by the web page creator. Because velocity is used as a view, because its syntax, functions, and usage are relatively simple, it is generally possible for page makers to master its usage within one day.

Ii. Basic velocity syntax

1. Declaration: # Set ($ Var = xxx)
The following content can be left
Variable reference
String Literal
Property Reference
Method reference
Number literal # Set ($ I = 1)
Arraylist # Set ($ arr = ["yt1", "T2"])
Arithmetic Operators
2. Notes:
Single line ## xxx
Multiple lines # * XXX
Xxx *#

3 variable Variables
It must start with "$" and the first character must be a letter. Character followed by a VTL identifier. (A. Z or a. Z). The variables can contain the following characters:
Alphabetic (A. Z, A. Z)
Numeric (0 .. 9)
Hyphen ("-")
Underscore ("_")

4. Properties
$ Identifier. identifier
$ User. Name
NAME value in hashtable user. For example: User. Get ("name ")
5. Method Methods
Object User. getname () = $ user. getname ()
6. Notes on regular reference formats: formal reference notation
Use {} to separate the variable name from the string, as shown in figure
# Set ($ user = "CSY "}
$ {User} Name
Return csyname
$ Username
$! Username
  $ And $! Difference
When the username cannot be found, $ username returns the string "$ username", while $! Username returns an empty string ""
7. Double quotation marks and quotation marks
# Set ($ Var = "HELO ")
Test "$ Var" returns testhello
Test' $ var 'returns test' $ var'
You can change the default processing mode by setting stringliterals. interpolate = false.
8. Condition statements
# If ($ Foo)
<Strong> velocity! </Strong>
# End
# If ($ Foo)
# Elseif ()
# Else
# End
When $ foo is null or a Boolean object's false value, it is executed.
9. logical operators: ==&||!
10. Loop statements

# Foreach ($ Varin $ arrays)

// The set contains the following three vectors: ahashtable or an array
# End
# Foreach ($ product in $ allproducts)
<Li> $ product </LI>
# End

# Foreach ($ key in $ allproducts. keyset ())
<Li> key: $ key-> value: $ allproducts. Get ($ key) </LI>
# End

# Foreach ($ customer in $ customerlist)
<Tr> <TD> $ velocitycount </TD> <TD> $ customer. Name </TD> </tr>
# End
11. The velocitycount variable is defined in the configuration file.
# Default name of the loop counter
# Variable reference.
Directive. foreach. Counter. Name = velocitycount
# Default starting value of the loop
# Counter variable reference.
Directive. foreach. Counter. Initial. value = 1
12. Include files
# Include ("one.gif", "two.txt", "three.htm ")
13. parse import script
# Parse ("me. VM ")
14. # Stop execution and return
15. Define the macro velocimacros, which is equivalent to the function supporting the inclusion Function

# Macro (d)
<Tr> <TD> </tr>
# End
Call
# D ()

Macro with Parameters
# Macro (tablerows $ color $ somelist)
# Foreach ($ something in $ somelist)
<Tr> <TD bgcolor = $ color> $ something </TD> </tr>
# End
# End
16. Range Operator
# Foreach ($ Foo in [1 .. 5])

17. "#" is the script statement used to identify velocity, including # Set, # If, # else, # End, # foreach, # End, # iinclude, # parse, # macro, etc;

For example:
# If ($ info. IMGs)

# Else

# End

18. "$" is used to identify an object (or be understood as a variable );

For example, $ I, $ MSG, $ tagutil. Options (...), etc.

19. "{}" is used to clearly identify the velocity variable;

For example, there is a $ someonename in the page. In this case, velocity uses someonename as the variable name. If our program wants to display the name character after the someone variable, then the label above should be changed to $ {someone} Name.

20 ,"! "Is used to forcibly display non-existent variables as blank.

For example, if the page contains $ MSG, the value of MSG is displayed if the MSG object has a value. If the MSG object does not exist, the $ MSG character is displayed on the page. This is not expected. In order to display a non-existent variable or an object whose value is null as a blank space, you only need to add a "!" before the variable name. . Example: $! MSG

3. easyjweb suggestions

Too many complex script expressions are used in the Interface Template. Do not add any complicated logic to the interface template as a last resort, do not add variable declaration or logical operators to the Interface Template. Easyjweb provides five basic template script statements to meet the requirements of all application templates. These four template statements are simple and can be directly added by the interface designer. In many easyjweb application practices, we can see that only the following four simple template script statements can be summarized in all interface templates:
1. $! OBJ returns the object result directly.
For example, the Java object MSG value is displayed in the HTML Tag. <P> $! MSG </P>
Display the value of the MSG object processed by the htmlutil object in the HTML tag <p >$! Htmlutil. dosomething ($! MSG) </P>

2. # If ($! OBJ) # else # End judgment statement
For example, in easyjweb open-source applications, we often see examples for pop-up message MSG.
# If ($ MSG)
<SCRIPT>
Alert ('$! MSG ');
</SCRIPT>
# End
The script indicates that when the object MSG object exists, the content after <SCRIPT> is output.

3. # foreach ($ info in $ list) $ info. somelist # End cyclically reads the objects in the list of sets and processes them accordingly.
For example, on the homepage of easyjf open-source forum system (0.3), HTML Interface Template scripts with hot topics are displayed:
# Foreach ($ info in $ hotlist1)
<A href = "/bbsdoc. EJF? Easyjwebcommand = show & cid = $! Info. CID "target =" _ blank ">$! Info. Title </a> <br>
# End
The preceding script traverses objects in the hotlist1 set cyclically and outputs related content of objects.
4. # macro (macroname) # End Script Function (macro) calls. It is not recommended to use them in a large number in the Interface Template.
For example, in the example of adding, deleting, modifying, and querying quickly generated by easyjwebtools, you can click the title bar of the List to display the results in ascending/descending order, this is a template content that we often see in easyjweb.
The function (macro) definition is generally placed at the very beginning. Case study:

# Macro (orderpic $ type)
# If ($ orderfield. Equals ($ type ))

# End
# End
For example, <font color = "# ffffff"> title # orderpic ("title") </font>

5. Include files # inclue ("template file name") or # parse ("template file name ")

It is mainly used to process pages with the same content, such as the top or tail content of each website. For example: # parse ("/blog/top.html") or # include ("/blog/top.html ")
The difference between parse and include is that if the included file contains the velocity script tag, it will be further parsed, and include will be displayed as is.

Iv. Example

When velocity is applied to a Java project, after creating a common Java project, you need to introduce the corresponding jar package for the Project to Support the velocity template engine (velocity-1.7.jar/commons-*. Jar)

1. Example 1:

The background Java code 'veljava. Java' of the veljava Project'

// Constructor

Public veljava () throws ioexception {

// Initialize the velocity Template

Velocity. INIT ();

// Create a veloctiycontext object

Velocitycontext context = new velocitycontext ();

// Add a key-value pair to the velocitycontext object

Context. Put ("list", getnames ());

Template template = NULL;

// Obtain a template using a static method

Template = velocity. gettemplate ("test. VM ");

// Create an output stream

Bufferedwriter writer = new bufferedwriter (New outputstreamwriter (system. Out ));

// Combine the template with the objects in the context and then output

If (template! = NULL)

Template. Merge (context, writer );

// Refresh the cache

Writer. Flush ();

// Close writer

Writer. Close ();

}

// The value in the velocitycontext key-Value Pair

Public arraylist <string> getnames (){

Arraylist <string> List = new arraylist <string> ();

List. Add ("element 1 ");

List. Add ("element 2 ");

List. Add ("element 3 ");

List. Add ("element 4 ");

Return list;

}

Remarks

In this example, the return value of the getnames () function is stored in the velocity container in the form of a healthy value pair, and a key value is given as list

The code for the template file is as follows: Test. VM:

# Declare a variable

# Set ($ this = "pptest ")

# Print out Variables

$ This is great!

# Scan the list in the background and print the elements in the set one by one

# Foreach ($ name in $ List)

$ Name is showed!

# End

# Setting a judgment condition will assign a true value to the judgment Condition

# Set ($ condition = true)

# Execute if the condition is true

# If ($ condition)

The condition is true!

# Execute when the condition is false

# Else

The condition is false!

# End

Remarks

# Indicates the annotation.

# The set class indicates preprocessing commands.

$ Variable name indicates that a variable is declared

The above code annotations are clear. If you only need to know more details about the application, the above Code is enough, from the code above, we can see that one advantage of velocity is that the template file can be developed in sync with the background file, as long as some common variable definitions are agreed, when the template is output, replace the variables by the template engine and then output the variables.

Example 2: velocity dynamic template creation and rendering (Java Project)

Demonstrate how to render the template in the Java project and output the template in the specified encoding mode GBK. It also shows how to dynamically create the template and then render it.

Public static void main (string [] ARGs ){

// Initialize the velocity Engine

Velocity. INIT ();

// Obtain a velocitycontext object

Velocitycontext context = new velocitycontext ();

// Add the corresponding key-value pair to the object container

Context. Put ("name", "velocity ");

Context. Put ("project", "Jakarta ");

// The bottom layer of stringwriter is actually a stringbuffer

Stringwriter W = new stringwriter ();

// Combine test2.vm and context to write the generated final code to the Buf of stringwriter.

Velocity. mergetemplate ("test2.vm", "GBK", context, W );

// Print it out on the console

System. Out. println ("template:" + W );

// Dynamically create a template

String S = "using $ project $ name rendering template ";

W = new stringwriter ();

/*

* Context: renders the input string.

* W: The output location of the rendered result.

* Mystring: When an error occurs, it is used as the name of the error file.

* S: Includes VTL input strings.

*/

Velocity. Evaluate (context, W, "mystring", S );

// Output the result

System. Out. println (w );

}

The template file test2.vm in example 2 is as follows:

Hello from $ name in the $ project.

Example 2 is very similar to Example 1. The example 2 template is only created in the Code. The template in Example 1 directly references the external test. VM file. From the above code, we can speculate on how velocity works.

1. Read external VM files into the memory

2. Velocity template engine parses VM files

3. After parsing, replace the variables in the template file and execute the corresponding judgment logic in the VM.

4. After the execution, the rendering result of the entire page will be known, and you can directly output the result.

From this we can see that as long as the front and back-end code developers can agree on the same variables, the front and back-end development can be executed in parallel.



Recommended articles: http://www.cnblogs.com/yasin/archive/2010/04/02/1703188.html

Http://www.yanyulin.info/pages/2014/03/velocity_disabuse_1.html

 

Getting started with velocity scripts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.