Nvelocity template engine

Source: Internet
Author: User

A. nvelocity is A. Net-based template engine ). It allows anyone to simply use the template language to reference objects defined by. Net code. Page designers can focus only on the display effect of the page, while. Net program developers focus on business logic encoding.

B. template engine processing process: compile a template-> process data-> render HTML.

C. nvelocity: http://www.castleproject.org/download/

D. A simple example:

Create an application, add a nvelocity reference to the project, add a new item, select a general processing program, name it login. ashx, and write the following code in the processrequest method:

Public void processrequest (httpcontext context) {context. response. contenttype = "text/html"; // whether to load string ispostback = context. request ["ispostback"]; If (string. isnullorempty (ispostback) {// create the nvelocity Instance Object velocityengine vltengine = new velocityengine (); vltengine. setproperty (runtimeconstants. resource_loader, "file"); // The template storage directory vltengine. setproperty (runtimeconstants. file_resource_loader_path, hostingenvironment. mappath ("/template"); vltengine. init (); // defines a template context. velocitycontext vltcontext = new velocitycontext (); // specifies the parameter vltcontext required by the input template. put ("username", ""); vltcontext. put ("password", ""); vltcontext. put ("MSG", "LOAD"); // obtain the template we just defined. The template directory template vlttemplate = vltengine has been set above. gettemplate ("login.htm"); // Based on the template context, write the content generated by the Template into the stringwriter vltwriter = new stringwriter (); vlttemplate. merge (vltcontext, vltwriter); string html = vltwriter. getstringbuilder (). tostring (); context. response. write (HTML );}}
View code

Response, code:

<HTML xmlns = "http://www.w3.org/1999/xhtml"> View code

Running HTML directly can only see the Template Effect. Our working principle is to read the template in the general processing program ashx to generate HTML and output it to the client browser, therefore, we need to access the general processing program ashx.

E. nvelocity template syntax

The background code is basically like that. The focus of nvelocity is how to compile a template that suits the requirements. In the above example, when put, the strings are used as an example, what if I put an object and a set?

1. Basic usage

Vltcontext. Put ("username", username );
$ Username can be referenced in the template.

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

2. Object Attributes

The following demonstrates some more advanced usage. Put an object directly and reference its attributes in the template. Nvelocity also supports object calling methods based on object attributes, which is like $ P. Name When referenced.

First define a C # class, person. CS

public class Person    {        public string name{ get; set; }        public string age { get; set; }    }
View code

Then, initialize the template and input in the. ashx file to be processed:

Person P = new person (); p. name = "dragon"; p. age = "11111"; // The parameter vltcontext required to pass in the template. put ("P", P );
View code

Call objects in the .htm file:

Username: <input type = "text" name = "username" value = "$ p. name "/> <br/> year & nbsp; age: <input type =" text "name =" password "value =" $ p. age "/> <br/>
View code

3. Object Index

Initialize the template and input in the. ashx file:

Dictionary <string, string> dict = new dictionary <string, string> (); dict ["name"] = "dragon"; dict ["Address"] = "Guangxi "; // input the parameter vltcontext required by the template. put ("dict", dict );
View code

Call objects in the .htm file:

$dict.name<br />$dict.address
View code

4. foreach Traversal

List

Initialize the template and input in the. ashx file:

// List type list <person> lstps = new list <person> (); lstps. add (new person {name = "dragon", age = "30"}); lstps. add (new person {name = "yyk", age = "28 "});
View code

Format:

# Foreach ($ element in $ List)

This is $ Element

# End

Call objects in the .htm file:

<ul>#foreach($p in $lstps)    <li>$p.name,$p.age</li>#end</ul>
View code

In the front-end template, if the background code is written, if it starts with #, for example, # foreach, because there is no braces, it is marked with # end at the end, foreach and if can also be nested, just as we usually write background code, but the syntax is a little different.

5. If judgment

Initialize the template and input in the. ashx file:

// Array string [] STRs = {"dragon", "Guangxi", "Web"}; // specifies the parameter vltcontext required for the input template. put ("STRs", STRs );
View code

Call objects in the .htm file:

Format:

# If (condition)
# Elseif (condition)
# Else
# End

<ul>#foreach($str in $strs)    #if ($str == "Dragon")    <li>$str</li>    #elseif($str == "guangxi")    <li>$str</li>    #end#end</ul>
View code

6. parse and include

As the name suggests, # include includes other templates in the template, such as the website header, tail, and advertisement template. When the content is the same, you can create a separate template for reference everywhere.

The velocity template uses the nvelocity variable $ body. The $ body variable can still be used in the template, but the # include variable cannot be used, and the related nvelocity elements (# foreach, # If) cannot work, it can only be output as is, so # parse> # stored ed.

7. Use # Set

In the front-end nvelocity code, we can declare a parameter for the front-end to avoid passing the background code again. For some simple logic, we can implement it like this.

Call objects in the .htm file:

# Set ($ A = 1 + 6) <P style = "text-align: Center"> the value of A is $ A </P>
View code

Code encapsulation using anonymous classes

For nvelocity, we should focus on compiling suitable templates. The background code is basically encapsulated once and can be called multiple times, you only need to make the object to be put into a variable parameter and encapsulate the remaining code. Therefore, we recommend that you use an anonymous class for better calling, because with the preparation of the template, we may need to transmit multiple types of data. The advantage of using an anonymous class is that class attributes are customized instead of being like a custom type, each time you add a data attribute, You have to modify the type, which is elegant and convenient.

// Anonymous class VaR models = new {head = new {Title = "Anonymous class test", head = "e-government system"}, foot = new {content = "technical support: dragon "}};
View code

 

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.