"Go" everyone should know the nvelocity usage

Source: Internet
Author: User

Nvelocity is a. Net-based template engine. It allows anyone to simply use the template language (templates language) to refer to by. NET code defines the object. So that the interface designers and. NET program developers are basically detached.

Original address: http://www.cnblogs.com/hxling/archive/2011/10/23/2221918.html

I. Brief introduction of common functions of nvelocity

1, define the variables in the page, and perform a simple operation.

2. Get a reference to the background program entity object in the page.

3. Iterate over the collection of entity objects in the page.

4. Get the properties of the entity object and its method in the page.

5. Support for logical judgment statements.

6. References to external files.

7, the external file parsing.

Second, the working principle of nvelocity

can be used. NET's reflection implementation. The following is a simple implementation of nvelocity for an iterative entity class:

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

2. List the people in the page, then enter the following code:

#foreach ($p in $ps)

<p> Welcome: $p .name</p>

#end

3, get the list of people, save in _list. and specifies that the string "PS" in the page corresponds to the _list.

4. Read the template file in text mode and match #foreach ... #end段, if matched to continue to match $x in $XX segment, record the characters used to save the collection and the item, respectively, this time is "P" and "PS".

5. Use the GetProperties () method of the type object to get all the properties of each item in the _list, and replace the value of the current object with the #foreach #end段中循环将 $p + property name. Of course, the method of invoking an object can also be obtained in the same way.

Three, basic grammar

1. Introduction of special characters

A, "#": means to start doing something.

B, "$": indicates what is used to obtain. (The expression "reference" begins with $) means to get something. Reference variable, property, method)

C, "# #": Single-line comment.

D, "#* ... *#": Multiline comment.

2. Key words

A, Set: Start doing something, such as defining variables, assigning values to variables, and so on. (Note: If the operand on the right is a reference to a property or command and returns NULL, the assignment will not succeed and cannot be removed in the subsequent vtl, and if it is to be used as an if condition, a workaround is to assign a value to the variable before assigning a reference to a property or command to the variable)

B, Foreach: Iteration statements

C, IF: Conditional judgment statement

D, Elseif

E, Else

F, Include: a reference to an external file, where the starting position is the template path.

G, Parse: a reference to an external file and parse it in a nvelocity manner.

H, macro: Create a macro, you can do something repeatedly, similar to the method.

I, even: even-numbered execution

J, Odd: singular execution

K, each: Execute every time

(Note: All variables cannot be used before they are defined (because we are used to the habit of having global variables), a valid VTL identifier begins with a letter: NET background, except for objects defined by the Template language is case-sensitive, all keywords must be lowercase, by default, nvelocity parsing is not case-insensitive, of course, can be set runtime.strict.math=true, using strict parsing mode. )

Iv. Examples of Use

1. Using Variables in the page

Define variable: #set ($a = "CNF")

Reference variable: Welcome: $a

Define variable: #set ($a = 1)

Operation: #set ($a = $a + 1)

Output: $a # #得: 2

Operation: #set ($a = $a)

Output: $a # #得: 10

#set ($criteria = ["Name", "Address"])

#foreach ($criterion in $criteria)

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

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

#if ($result)

Query was successful

#end

#end

(Note: From the above you can see that the substitution order of nvelocity is basically consistent with the execution of. NET program code, which can be summed if placed in a foreach statement block.) Use the IF statement to get the line number and special handling of the contents of the special line number. All variables cannot be used before they are defined. NET background objects, preferably in the formal reference format, ${a}, the formal reference format is generally used to directly adjust the string content in the template; static reference output: Nvelocity encountered a reference that cannot be processed, generally he will directly output this reference to the wording of the text, the page will see the $ Email, we can add a! Number to the back, then the output will be blank. $! {Email} if not processed, it will output white space. If the email is defined (for example, its value is foo), here you want to export the $email. Such a string, you need to use the escape character "\", such as: \ $email)

2. Use conditional judgment statements in the page

#if ($p. Strsex = = "female")

#set ($Sex = "Lady")

#elseif ($p. Strsex = = "Male")

#set ($Sex = "sir")

#elseif ($p. Strsex = = "None")

#set ($Sex = "Shemale")

#else

#set ($Sex = "Monster")

#end

(Note: You can nest in a foreach statement block to perform special display processing for each list object.) )

3, create a macro, can be used as a method.

Created: #macro (Add $a $b)

#set ($c = $a + $b)

<p> Final results: $c </p>

#end

Call: #Add (1 2)

(Note: There are 3 initialization methods for the template engine, one for the template file and one for the template file address.) Results found with template file content, when the application of macros seems to be a bit of a problem. The other is that if you add a judgment statement to a macro, you can implement a recursive call. )

4. Using Object methods

Define variable: #set ($str = "CNF")

Calling method: $str. SubString (0,1)

Output: C

Define variable: #set ($a = 123)

Calling method: $a. GetType ()

Output: System.Int32

(Note: either. NET code, or the variables defined by the designer in the page, can use the methods and properties of the object, which is very powerful. )

5. Use even and odd to simplify the code, each auxiliary

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

#foreach ($p in $ps)

#even

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

#odd

<p> Line: $p .strname</p>

#end

(Note: When using these two keywords, there is the same problem as creating a macro, that is, when initializing the template indexing engine, if it is initialized with the template file content, there will be problems)

6. Referencing external files

Both include and parse have the effect of introducing an external file, but the parse will parse the external file according to the Nvelocity template language. This means that if the current template is introduced, a dead loop will occur.

The #include script element allows the template designer to introduce a local file into the template, and the introduced file will not be parsed by nvelocity. To be safe, the file that can be placed is simply the configuration parameter template_root the directory defined in the current directory.

#include ("head.html")

If you need to introduce multiple files, you can do just the following.

#include ("One.gif", "Two.txt", "three.htm")

Of course, a variable name can also be used instead of the file name introduction.

#include ("Greetings.txt", $seasonalstock)

The #parse element indicates that a local file containing TVL can be introduced and the file will be parsed out by the Nveloict engine.

#parse ("ME.VM")

Unlike #include directives, #parse can get variable references from the introduced template. But the #parse directive can only accept one parameter. The VTL templates #parse template can also contain the #parse declaration, the default depth is 10, This is determined by the configuration parameters directive.parse.max.depth in the file velocity.properties, which you can modify to fit the project requirements.

7. Using the foreach statement

The foreach statement is listed more than once, and I believe it is known to work. That is, the loop lists a collection of objects. For example: #foreach ($p in $ps), where $ps needs to correspond to a specific entity class name in the background code, $p represents one of the $ps. As mentioned above, $p can invoke the properties and methods of an entity class.

(Note: The #foreach statement must end with #end, and the counter provided by the nvelocity can be accessed by referencing the variable $velocitycount:)

8. Creating an array

Created: #set ($List = ["Male", "female"])

Traversal: #foreach ($Item in $List)

<p>list Members: $Item </p>

#end

Output: List member: Male

List member: female

Provide a nvelocity operation class Velocityhelper, convenient for everyone to use: Click to download

NVelocity.dll Download: Click to download

The Velocityhelper call is as follows:

Velocityhelper VH = new Velocityhelper ();

Vh.    Init ("~/template/"); Template path

Vh. Put ("templatevariable", Variable);

Vh. Display ("index.htm");

Attached: nvelocity Common grammar instruction

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

In Nvelocity, a reference to a variable is preceded by a variable name. When used! Indicates that an empty string is displayed when the value of this variable is null. For example, when $article is empty, it will show "$article" and $!article will appear as "". {} is qualified for the variable name, and sometimes the variable name will have a string, which requires {}. For example $articleshow, want to refer to $article, this time as long as modified as ${article} can. In fact, Nvelocity will become this mode after parsing the entire template.

A reference to a property: $ [{] [a]. Z, A.. Z [A]. Z, A.. Z, 0..9,-, _]*. [A.. Z, A.. Z [A]. Z, A-Z, 0..9,-, _]* [}].

such as $article. Title or ${article. Title}.

A reference to the method: $ [{] [a]. Z, A.. Z [A]. Z, A.. Z, 0..9,-, _]*. [A.. Z, A.. Z [A]. Z, A.. Z, 0..9,-, _]* ([optional parameter list ...]) [ } ]。

For example: $article. Getlistbytitle (' nvelocity ') or ${article. Getlistbytitle (' Nvelocity ')}. In fact, the property value of the object can also be obtained with $article.get_title ().

Assignment instruction #set:# [{] set [}] ($ref = [", ']arg[", ']).

For example: $article. Title= ' nvelocity ', $ $article. categories=[1,2,3], of course, the right side can also use complex expressions: $article. Title= $otherArticle. title.substring (0,3), arithmetic expression: $article. PAGE=4/3 and so on. Property assignment can also be used with $article.set_title (' nvelocity ').

Conditional directive #if:# [{] if [}] ([condition]) [OUTPUT] [# [{] ElseIf [}] ([condition]) [Output]]* [# [{] else [}] [Output]] # [{] end [}].

The condition can be a review expression that returns BOOL. For example: #if ($article. total>1) $article. Title #else no data #end.

Loop instruction #foreach:# [{] foreach [}] ($refinarg) statement# [{] end [}].

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

Reference static resource directive #include:# [{] include [}] (arg[arg2 ... argn]).

For example: #include (' tmp.js '), the contents of the Tmp.js file are inserted into the current stream. Of course you can use an expression: #include ($article. URL).

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

For example: #parse (' tmp.js '), unlike # include, if the Tmp.js file has nvelocity instructions, the variable is processed and the result is inserted into the current stream.

Stop instruction #stop:# [{] stop [}].

When nvelocity resolves to this directive, the parsing process is stopped. General user Debugging.

Computes the instruction #evaluate:# [{] Evaluate [}] (ARG).

For example: #evaluate (' $article. Title '), which will be $article in the current output. Title

The workaround for nvelocity $ with jquery conflicts is as follows:
1.
Use Jquery.noconflict. such as: var j = jquery.noconflict (); J.ajax ();
Cons: When using jquery's related plugins, it will invalidate the plugin!
2.
Use jquery instead of $. such as: Jquery.ajax ();
Cons: Not suitable for expansion, once replaced with a third-party library, it is troublesome
3.
Wrap jquery in the conflict method.
If $.ajax () conflicts in velocity, it is redefined as follows:
function DW () {}
Dw.ajax=function (s) {Jquery.ajax (s);} dw.ajax ();
4.
Define a $JQ of $. In the future in JS can be used ${jq}ajax.
Write in the foreground (definition): #set ($JQ = "$.")

"Go" everyone should know the nvelocity usage

Related Article

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.