Nvelocity usage that everyone should know

Source: Internet
Author: User

Nvelocity is A. Net-based template engine ). It allows anyone to simply use the template language to referenceCodeDefined Object. So that the interface designer and. netProgramDevelopers are basically separated.

I. Introduction to common nvelocity Functions

1. Define variables on the page and perform simple operations.

2. obtain reference to the background program object on the page.

3. iterate the object set on the page.

4. Obtain the attributes and methods of the object on the page.

5. Support for logical judgment statements.

6. References to external files.

7. parsing external files.

Ii. How nvelocity works

You can use. Net reflection. The following are simple steps for nvelocity to implement iterative entity classes:

1. Define the people class and have the name and sex attributes. Represents a person.

2. To list characters on the page, enter the following code:

# Foreach ($ P in $ PS)

<P> welcome: $ P. Name </P>

# End

3. Obtain the character list and save it to _ list. And specify the string "Ps" corresponding to _ list in the page.

4. Read the template file in text format and match # foreach... # End segment. If it matches, the $ X in $ XX segment will be matched. The records are used to save the characters of the set and individual items. This time is "P" and "Ps ".

5. Use the getproperties () method of the type object to obtain all the attributes of each item in _ list, in the # foreach # End Section, replace the $ P + attribute name with the current attribute value of the current object. Of course, if you want to call the object method, you can also get it in the same way.

III. Basic syntax

1. special characters

A. "#" indicates what to start.

B. "$" indicates what is used for obtaining. ("Reference" starting with "$" means obtaining some stuff. variables, attributes, and methods can be referenced)

C. "#": single-line comment.

D. "# *… ... * # ": Multi-line comment.

2. Keywords

A. Set: start to do something, such as defining variables and assigning values to variables. (Note: If the right operand is a reference to an attribute or command and null is returned, the value assignment will not be successful and cannot be taken out and used in subsequent VTL, if you want to use the if condition, a solution is to first assign a value to the variable, and then assign a reference to the attribute or command to the variable)

B. foreach: iterative statement

C. If: Condition judgment statement

D. elseif

E. Else

F. include: References to external files. the start position is the template path.

G. parse: References to external files and resolves them in nvelocity mode.

H. Macro: Create a macro. You can repeat something, similar to a method.

I. Even: double execution

J. Odd: singular execution

K. Each: run every time

(Note: all variables cannot be used before they are undefined (because we are used to using global variables). A valid VTL identifier starts with a letter .. Except for objects defined in the net background. The template language is case-sensitive. All keywords MUST be lowercase. By default, nvelocity resolution is case-insensitive. Of course, you can set runtime. strict. math = true, use the strict resolution mode .)

Iv. Example

1. Use variables on the page

Define the variable: # Set ($ A = "CNF ")

Reference variable: Welcome: $

Define variable: # Set ($ A = 1)

Operation: # Set ($ A = $ A + 1)

Output: $ A ##: 2

Operation: # Set ($ A = $ A * 5)

Output: $ A ##: 10

# Set ($ criteria = ["name", "Address"])

# Foreach ($ criterion in $ criteria)

# Set ($ result = false) // set the default value first

# Set ($ result = $ query. Criteria ($ criterion ))

# If ($ result)

Query was successful

# End

# End

(Note: from the above, we can see that the replacement sequence of nvelocity is basically the same as that of the. NET program code. If it is placed in the foreach statement block, it can be accumulated. Use the if statement to obtain the row number and perform special processing on the content of the special row number. All variables cannot be used before they are undefined ,. except for net background objects, it is best to use the regular reference format $ {A}. The regular reference format is generally used to directly adjust the string content in the template; static reference output: when nvelocity encounters a reference that cannot be processed, it usually outputs the $ email reference method directly, and $ email is displayed on the page. We can add one after $! No., then the white space will be output. $! {Email} is blank if it cannot be processed. If the email has been defined (for example, its value is foo), but here you want to output $ email. to use such a string, you must use the Escape Character "\", for example, \ $ email)

2. Use the condition judgment Statement on the page

# If ($ P. strsex = "")

# Set ($ sex = "Ms ")

# Elseif ($ P. strsex = "male ")

# Set ($ sex = "Mr ")

# Elseif ($ P. strsex = "")

# Set ($ sex = "demon ")

# Else

# Set ($ sex = "monster ")

# End

(Note: It can be nested in the foreach statement block for special display and processing of each list object .)

3. Create a macro and use it as a method.

Create: # macro (add $ A $ B)

# Set ($ c = $ A + $ B)

<P> final result: $ C </P>

# End

Call: # Add (1 2)

(Note: There are three initialization methods for the template engine. One is the template file content, and the other is the template file address. The results showed that the content of the template file seemed to be a problem when applying macros. In addition, if a judgment statement is added to the macro, recursive calling can be implemented .)

4. Object Method

Define the variable: # Set ($ STR = "CNF ")

Call method: $ Str. substring (0, 1)

Output: c

Define variable: # Set ($ A = 123)

Call method: $ A. GetType ()

Output: system. int32

(Note: whether it is an object defined by. Net code or a variable defined by the designer on the page, the method and attributes of the object can be used, which is very powerful .)

5. Use even and odd to simplify the code.

As mentioned above, the IF statement can be used to create different styles for each row in the list. However, if you only need to distinguish between single and double rows, you can use even and odd to simplify the code. As follows:

# Foreach ($ P in $ PS)

# Even

<P> double row: $ P. strname </P>

# Odd

<P> single row: $ P. strname </P>

# End

(Note: when using these two keywords, the problem is the same as creating a macro, that is, when initializing the template engine, if the template file content is initialized, problems may occur)

6. Reference external files

Both include and parse can introduce external files. The difference is that parse will parse external files according to the nvelocity template language. That is to say, if the current template is introduced, an endless loop will occur.

# The include script element allows the template designer to introduce a local file in the template. The imported file will not be parsed by nvelocity. for security reasons, the files that can be cited are only in the directory defined by the configuration parameter template_root, which is in the current directory by default.

# Include ("head.html ")

If you need to introduce multiple files, you can do as follows.

# Include ("one.gif", "two.txt", "three.htm ")

Of course, a variable name can also be used to introduce the file name.

# Include ("greetings.txt", $ seasonalstock)

# The parse element indicates that a local file containing TVL can be introduced, which will be parsed and output by the nveloict engine.

# Parse ("me. VM ")

Unlike the # include command, # parse can get variable reference from the introduced template. however, the # parse command can only accept one parameter. VTL templates can be included in # parse templates. The default depth is 10, which is determined by the configuration parameter directive. parse. max. depth in the file velocity. properties, you can modify it to suit the project requirements.

7. Use the foreach statement

The foreach statement has been listed multiple times above, and I believe it is useful. A set of objects is displayed cyclically. For example: # foreach ($ P in $ PS), where $ PS must correspond to the specific object class name in the background code, $ p represents one of $ ps. As mentioned above, $ P can call attributes and methods of object classes.

(Note: # The foreach statement must end with # end. You can access the counters provided by nvelocity by referencing the variable $ velocitycount :)

8. Create an array

Create: # Set ($ list = ["male", "female"])

Traversal: # foreach ($ item in $ List)

<P> List member: $ item </P>

# End

Output: List member: Male

List member: Female

Provides an nvelocity operation class velocityhelper for your convenience: Click to download

Download nvelocity. dll: Click to download

Velocityhelper is called as follows:

Velocityhelper VL = new velocityhelper ();

Vl. INIT ("~ /Template/"); // template path

Vl. Put ("templatevariable", variable );

Vl. Display ("index.htm ");

Appendix: nvelocity common syntax commands

Variable reference: $ [! ] [{] [A. Z, A. Z] [A. Z, A. Z, 0. 9,-, _] [}].

In nvelocity, variables are referenced starting with $ with a variable name. When used! When the variable value is null, an empty string is displayed. For example, if $ article is empty, "$ article" is displayed, while $! Article is displayed as "". {} Is the variable name restriction. Sometimes there is a string after the variable name, which requires. For example, if you want to reference $ article in $ articleshow, you only need to change it to $ {Article. In fact, nvelocity will change to this mode after parsing the entire template.

Attribute reference: $ [{] [.. z, .. z] [.. z, .. z, 0 .. 9,-, _] *. [.. z, .. z] [.. z, A-Z, 0 .. 9,-, _] * [}].

For example, $ article. Title or $ {Article. Title }.

Reference to a method: $ [{] [.. z, .. z] [.. z, .. z, 0 .. 9,-, _] *. [.. z, .. z] [.. z, .. z, 0 .. 9,-, _] * ([optional parameter list...]) [}].

For example, $ article. getlistbytitle ('nvelocity ') or $ {Article. getlistbytitle ('nvelocity ')}. In fact, you can use $ article. get_title () to obtain the object property value.

Value assignment command # Set: # [{] Set [}] ($ ref = [", '] Arg [",']).

Example: $ article. title = 'nvelocity ', $ article. categories = [1, 2, 3]. Of course, you can also use a complex expression on the right: $ article. title = $ otherArticle. title. substring (0, 3), arithmetic expression: $ article. page = 4/3 and so on. You can also use $ article. set_title ('nvelocity ') to assign values to attributes ').

Condition command # If: # [{] If [}] ([condition]) [Output] [# [{] elseif [}] ([condition]) [Output] * [# [{] else [}] [Output] # [{] end [}].

The condition can be the review expression of the returned bool. For example: # If ($ article. Total> 1) $ article. Title # else has no data # End.

Loop command # foreach: # [{] foreach [}] ($ refinarg) Statement # [{] end [}].

For example: # foreach ($ article in $ articles) $ article. Title # End.

Reference static resource commands # include: # [{] include [}] (ARG [arg2... argn]).

For example, # include ('tmp. js') inserts the content of the TMP. js file into the current stream. Of course, you can use the expression # include ($ article. URL ).

Reference and parse the resource command # parse: # [{] parse [}] (ARG ).

Example: # parse ('tmp. js'), different from # include, if TMP. the JS file contains nvelocity commands, which process the variables and insert the results to the current stream.

Stop command # Stop: # [{] Stop [}].

When nvelocity resolves to this command, the parsing process is stopped. Debugging by users.

Calculation command # evaluate: # [{] evaluate [}] (ARG ).

For example: # evaluate ('$ article. title'), $ article. Title is output at the moment.

When the $ of nvelocity conflicts with the $ of jquery, the following solutions are provided:
1,
Use jquery. noconflict. For example, var j = jquery. noconflict (); J. Ajax ();
Disadvantage: When jquery plug-ins are used, the plug-ins will become invalid!
2,
Use jquery instead of $. For example: jquery. Ajax ();
Disadvantage: it is not suitable for expansion. If it is replaced with a third-party library, it will be difficult.
3,
The conflict method in wrap jquery.
For example, if $. Ajax () Conflicts in velocity, the definition is as follows:
Function DW (){}
DW. Ajax = function (s) {jquery. Ajax (s) ;}dw. Ajax ();
4,
Define a $ JQ as $. You can use $ {JQ} Ajax in JS later.
Write (defined) in the foreground as follows: # Set ($ JQ = "$ .")

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.