Well-known nvelocity usage

Source: Internet
Author: User

By default, nvelocity resolution is case-insensitive. Of course, you can set runtime. Strict. Math = true to use the strict resolution mode.

# Specify Username

Welcome: $ customer. Name!

<Table>

### Output user-preferred mud

# Foreach ($ mud in $ mudsonspecial)

# If ($ customer. haspurchased ($ mud ))

<Tr>

<TD>

$ Flogger. getpromo ($ mud)

</TD>

</Tr>

# End

# End

</Table>

SetThe indicator uses an expression (expression) (included in a pair of parentheses)-returns a valueValue(Here Is velocity) to variable A, (variable name on the left, value on the right, combined with = ).

The expression "reference" starting with "$" means to get some stuff. variables, attributes, and methods that can be referenced

The command that can reference the property to an object. velocity selects referenced commands using appropriate policies. it will be searched based on the protocol command format. whether the name referenced by the attribute is case-insensitive, velocity has a fixed search rule. for example$ Customer. AddressWhen referencing, the search order is:

Getaddress ()

Getaddress ()

Get ("Address ")

Isaddress ()

The attribute name address reference in VTL will be:

Getaddress ()

Getaddress ()

Get ("Address ")

Isaddress ()

Regular reference format

$ {Mudslinger}

1. Jack is a $ vicemaniac.

2. Jack is a $ {Vice} maniac.

In this way, velocity knows what you want$ ViceInstead$ VicemaniacVariable. The regular reference format is generally used to directly adjust the string content in the template.

Quiet reference notation(Static reference output)

When velocity encounters a reference that cannot be processed, it usually outputs the $ email reference method directly. $ email is displayed on the page, as shown in the following example, we can add one after $! Then the output is blank :.

<Input type = "text" name = "email" value = "$ email"/>

<Input type = "text" name = "email" value = "$! Email "/>

The official statement is :.

<Input type = "text" name = "email" value = "$! {Email} "/>

Getting literal (Semantic issues)

Velocity uses the $, # character to mark its declaration. However, sometimes such characters are written in HTML due to some other intent.

1. Currency (currency sign)

For example, USD $2.50! This method appears in the template. When VTL is processed, no error occurs and $2.50 is output correctly! The result you want. Why? A valid VTL identifier starts with a letter

As shown below, if there is no # Set ($ email = "foo") line and the context object in the Java code does not include an email object, $ email is directly output.

# Set ($ email = "foo ")

$ Email

If the email has been defined (for example, its value isFoo), But here you want to output$ Email. To use such a string, you must use the Escape Character "\".

# The following line defines $ email in this template:

# Set ($ email = "foo ")

$ Email

\ $ Email

\ $ Email

\\\$ Email

The preceding template output on the web page will be:

Foo

$ Email

\ Foo

\ $ Email

However, if the email is not defined, we write as follows :.

$ Email

\ $ Email

\ $ Email

\\\$ Email

The output will remain intact:

$ Email

\ $ Email

\ $ Email

\\\$ Email

Note: When a defined variable and an undefined variable are output together, the literal meaning is displayed as follows. $ moon is undefined:

# Set ($ Foo = "gibbous ")

$ Moon = $ foo

Output to the web page will be

$ Moon = gibbou

Case substitution (Optional format)

$ Foo. getbar ()

# Equivalent

$ Foo. Bar

$ Data. setuser ("Jon ")

# Equivalent

# Set ($ data. User = "Jon ")

$ Data. getrequest (). getservername ()

# Equivalent

$ Data. Request. servername

# Is the same

$ {Data. Request. servername}

Command: (directives) It starts with "#" And indicates "What actions.

# Set ($ monkey = $ Bill) # variable reference

# Set ($ monkey. Friend = "Monica") # string literal

# Set ($ monkey. Blame = $ Whitehouse. Leak) # Property Reference

# Set ($ monkey. Plan = $ spindoctor. Weave ($ web) # method reference

# Set ($ monkey. Number = 123) # Number literal

# Set ($ monkey. Say = ["not", $ my, "fault"]) # arraylist

# Set ($ monkey. Map = {"banana": "Good", "roast beef": "bad"}) # Map

Note: If the right operand is a reference to an attribute or command and null is returned, the value assignment will not succeed and cannot be retrieved and used in subsequent VTL

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

# Foreach ($ criterion in $ criteria)

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

# If ($ result)

Query was successful

# End

# End

In the preceding example, if ($ result) cannot be used to determine whether the query is successful.$ Result1.# SetNull(The context will be the same), it will not be assignedOther values(Cannot be retrieved from context ).

One solution is$ ResultSetFalse. If$ Query. Criteria ()If the call is successful, the system can detect it.

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

# Foreach ($ criterion in $ criteria)

# Set ($ result = false)

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

# If ($ result)

Query was successful

# End

# End

Note:# SetNot Required# EndTo declare the end.

Use# SetWhen the command is run, the variable will be parsed if "" is used, for example:

# Set ($ directoryroot = "www ")

# Set ($ templatename = "index. VM ")

# Set ($ template = "$ directoryroot/$ templatename ")

$ Template

The output will be:

WWW/index. VM

But when it is caused by single quotes, it will not be parsed ::

# Set ($ Foo = "bar ")

$ Foo

# Set ($ blargh = '$ foo ')

$ Blargh

The output will be:

Bar

$ Foo

By default, variables in single quotes are not parsed. Of course, this can be changed by changing the Configuration Parameter of velocity:

Velocity. properties such that stringliterals. interpolate = false.

By referencing the variable $ velocitycount, you can access the counters provided by velocity:

<Table>

# Foreach ($ customer in $ customerlist)

<Tr> <TD> $ velocitycount </TD> <TD> $ customer. Name </TD> </tr>

# End

</Table>

# IncludeThe script element allows the template designer to introduce a local file in the template. The introduced file will not be parsed by velocity. 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 ("one.txt ")

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)

# ParseElement indicates that a local file containing TVL can be introduced, which will be parsed and output by veloict engine ..

# Parse ("me. VM ")

And# IncludeDifferent commands,# ParseVariable reference can be obtained from the introduced template. However, the # parse command can only accept one parameter.

VTL templates is# ParseCan also include# ParseThe default depth is 10, which is determined by the configuration parameters.Directive. parse. Max. DepthIn the fileVelocity. PropertiesYou can modify it to suit the project requirements.

# StopThe command is used to indicate that the engine stops parsing somewhere in the template, which is generally used for calling. It is easy to use.

Velocimacros (macro call)

# MacroThe Directive allows template designers to define duplicate and related script versions as a function block. no matter under what circumstances. velocimacro designed with a single intent can minimize errors in template writing. Let's take a look at the example to understand the concept of velocimacros.

# Macro (d)

<Tr> <TD> </tr>

# End

In this way, a macro named D is defined, which can be referenced directly in Other templates as follows:

# D ()

Velocimacro can receive any number of input parameters from 0. in the preceding example, there are 0 parameters, but when it is called, the same number of parameters must be input. A macro with two parameters is defined here.

# Macro (tablerows $ color $ somelist)

# Foreach ($ something in $ somelist)

<Tr> <TD bgcolor = $ color> $ something </TD> </tr>

# End

# End

Then, we will use the following on the page:

# Set ($ greatlakes = ["superior", "Michigan", "Huron", "Erie", "Ontario"])

# Set ($ color = "blue ")

<Table>

# Tablerows ($ color $ greatlakes)

</Table>

Note Variables$ GreatlakesReplace macro variables$ SomelistThe final output is as follows:

<Table>

<Tr> <TD bgcolor = "blue"> superior </TD> </tr>

<Tr> <TD bgcolor = "blue"> Michigan </TD> </tr>

<Tr> <TD bgcolor = "blue"> Huron </TD> </tr>

<Tr> <TD bgcolor = "blue"> Erie </TD> </tr>

<Tr> <TD bgcolor = "blue"> Ontario </TD> </tr>

</Table>

Macros are defined in templates. How can we call other templates on the site? It would be great to define a macro that can be shared in a larger scope.

If you set macro # tablerows ($ color $ List)Define it to a template library (velocimacros Template Library), and other templates can access it.

Velocimacro arguments(Macro parameters)

Velocimacros can accept the following parameters from TVL:

  • Reference Type: All values starting with '$'
  • String Literal: something like "$ foo" Or 'hello'
  • Number literal: 1, 2 etc
  • Integerrange: [1 .. 2] or [$ FOO... $ bar]
  • Objectarray: ["A", "B", "C"]
  • Boolean value true
  • Boolean value false

When you pass a reference parameter to a macro, the reference is passed through the name ('pass by name ').

# Macro (callme $)

$

# End

# Callme ($ Foo. Bar ())

In the preceding example, bar () is called 3 times.

Finally, this feature is hard to learn, but when you carefully plan your macro library, eliminate scripts with repeated features in VTL-you can use macros like using an object or component. For example, a macro object generates repeated colors for multiple tables.

If you want to use this feature, you only need to pass a value to it in the following simple encoding:

# Set ($ myval = $ Foo. Bar ())

# Callme ($ myval)

Velocimacro properties (Macro attributes)

The configuration file velocity. properties contains multiple related configurations. For details, see the velocity Java Development guide Chinese edition.

Velocimacro. Library-specifies the global macro library. Multiple macros can be separated by numbers.

Velocimacro. permissions. Allow. inline-the default value is true, which allows macros to be defined in a formal template file.

Velocimacro. permissions. Allow. inline. to. Replace. Global-specifies whether the macro function defined in the template should replace the global library. The default value is false.

Velocimacro. permissions. Allow. inline. Local. Scope-whether the macro scope defined in the template is only available in this template.

Velocimacro. context. localscope-if it is true, when the macro passes # Set Value assignment. the Macro will keep one and will not change because the data in the context is modified. Similarly, the modifications in the macro will not change the data in the context.

Velocimacro. Library. autoreload-whether to automatically reload the file to debug the environment. The default value is false. For example, if it is true, you need to remove chcheing:. file. Resource. loader. cache = false ).

Some details:

Macros must be defined before the # macro () command in the template.

Do not directly use the # parse () include # macro () command in the template. Because the # parse () action is executed at runtime, there will be a process of searching for elements in the VM.

Two annotation methods:

##

#*...... *#

Velocimacro miscellany (macro problems)

This is a summary of some short questions. Maybe you should first have the concept of. 'velocimacro ', like a 'vm '.

Can I use one indicator as another indicator for operation?

For example: # Center (# bold ("hello "))

No. The indicator is not a valid parameter, but you can implement what you want as follows:

# Set ($ stuff = "# bold ('hello ')")

# Center ($ stuff)

Or:

# Center ("# bold ('hello ')")

Can I use # parse () to register a macro?

Macros must be defined before the template is used. we have a previous suggestion on this issue. # parse () is executed at runtime. The JVM does not necessarily search for objects in the sequence we expected.

String concatenation (link string)

The example is as follows:

# Set ($ size = "big ")

# Set ($ name = "Ben ")

The clock is $ size $ name.

The output above will be

'The clock is bigben '.

Or:

# Set ($ size = "big ")

# Set ($ name = "Ben ")

# Set ($ clock = "$ size $ name ")

The clock is $ clock.

They are all the same output. The last example is as follows ,:

# Set ($ size = "big ")

# Set ($ name = "Ben ")

# Set ($ clock = "$ {size} tall $ name ")

The clock is $ clock.

The output will be

'The clock is bigtallben '.

Layout application:

First, layout motherboard page

$ Childcontent

Then, in the subpage

# Capturefor(Title) Home Page# End

# Capturefor(Scripts)

<! -- Here you can include some inline JavaScript that will be added to the

Function sayhello ()

{

Return alert ("hello ");

}

# End

# Capturefor(Head)

<! -- Here you can include some content to appear on the layout, inside head. For example, stylesheets -->

# End

Table row parity style transformation

# Foreach ($ test in $ tests)

# Even

<Tr class = "test1">

# Odd

<Tr class = "Test2">

# Each

<TD> $ test. Name </TD>

<Tr>

# End

 

Appendix: nvelocity common syntax commands

References to variables:$ [! ] [{] [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 methods: $ [{] [.. 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 ').

 

Conditional instruction # 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 resource commands # 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.

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.