ASP. NET -- NVelocity (1), asp. netnvelocity

Source: Internet
Author: User

ASP. NET -- NVelocity (1), asp. netnvelocity

The template engine (specifically the template engine used for Web development) is generated to separate the user interface from the business data (content). It can generate documents in a specific format, the template engine for websites generates a standard HTML document. Today we will mainly introduce the NVelocity template engine.

1. Definition of NVelocity

NVelocity is A. NET-based template engine ). It allows anyone to simply use the template language to reference objects defined by. NET code. As a result, the interface designers and. NET program developers are basically separated.

Ø basic syntax

1. Add the # sign before the keyword (for example: # if... # End and # foreach ()... # End)

2. Add $ in front of the variable. For example, $ P indicates referencing the Variable p; "$" indicates what is used for obtaining. ("Reference" starting with "$" means obtaining some stuff. variables, attributes, and methods can be referenced.) (similar to JQuery, if you use $ at the same time, do not use a simple symbol instead of jQuery. Solve naming conflicts using jQuery. noConflict and other methods ).

3. there are two ways to reference an external file: # include and # parse, Include: Reference to an external file, starting from the template path; Parse: Reference to an external file, use the nVelocity Method for parsing. 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.

Other syntax, see http://blog.csdn.net/educast/article/details/6285180

Ø running logic

NVelocity uses the ing code to map data (which can be customized or retrieved from the database). The next article describes the interaction with the database. This section mainly describes the filling of Custom Data) to the template (usually html pages) for data filling, rendering it into a standard html page, then returning a pure html page string and handing it to HttpHandler, it is returned to the client browser for resolution (all logic judgments are completed by HttpHandler, which is a general processing program ).

2. NVelocity application Ø Reference Method

Use NVelocity to first download its DLL. Download link:Http://download.csdn.net/detail/dragonsq1009/3666832

Add it to the created Project, drag it to the project, and then add a reference to it.

Examples

It is best not to name a new project as NVelocity, because if it is the same as the Assembly name, that is, your reference set name, when you create a general handler or template page (html page) under a project, there will be an assembly conflict, so it is best not to have the same name as the assembly.

The first simple example

Step 1: create a general Handler

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> using NVelocity. app; using NVelocity. runtime; using System. collections. generic; using System. linq; using System. web; namespace NVelocity {// <summary> // login abstract description /// </summary> public class login: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; </span> </strong>
<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <span style = "white-space: pre "> </span> // instantiate a class and declare an object <span style =" white-space: pre "> </span> person = new person (); person. name = "lxn"; person. age = 25; VelocityEngine vltEngine = new VelocityEngine (); // initialize the vltEngine engine. setProperty (RuntimeConstants. RESOURCE_LOADER, "file"); // sets the parameter. The template is located in vltEngine of the file system. setProperty (RuntimeConstants. FILE_RESOURCE_LOADER_PATH, System. Web. Hosting. HostingEnvironment. MapPath ("~ /Templates "); // The folder where the template is located. Map the server path to the physical path vltEngine. init (); // The engine initializes VelocityContext vltContext = new VelocityContext (); // creates a context to transmit data using vltContext. put ("p", person); // set the parameter. You can use $ data to reference the parameter in the Template and assign the following value to the previous variable Template vltTemplate = vltEngine. getTemplate ("test.html"); // set the template System. IO. stringWriter vltWriter = new System. IO. stringWriter (); vltTemplate. merge (vltContext, vltWriter); string html = vltWriter. getStringBuilder (). toString (); // The replaced html Content context. response. write (html); // directly output} public bool IsReusable {get {return false ;}}}</span> </strong>

Step 2: Create a template page html

<strong><span style="font-family:Microsoft YaHei;font-size:14px;"><!DOCTYPE html>

Step 3: Create a person class

<strong><span style="font-family:Microsoft YaHei;font-size:14px;">using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace NVelocity{    public class person    {        public string Name { get; set; }        public int Age { get; set; }    }}</span></strong>

Then we make the corresponding request in the browser, that is, the general request processing page. If the default document or startup document is not set on iis, there will be no directory browsing, in this case, enter the name of the general handler.

In the above example, we create a person class, assign values to it in a general processing program, and then assign it to the template (html) for data filling and rendering it into an html page, the generated plain html text is returned to the general handler, and the general handler returns it to the browser for resolution and display.

Example 2: How to traverse and display elements in an array or set and reference external files

General Handler

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> using NVelocity; using NVelocity. app; using NVelocity. runtime; using System. collections. generic; using System. linq; using System. web; namespace engine {// <summary> // login2 abstract description /// </summary> public class login2: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; <sp An style = "margin: 0px; padding: 0px; border: none; line-height: 18px;"> // define data dictionary </span> <span style = "margin: 0px; padding: 0px; border: none; line-height: 18px; "> </span> Dictionary <string, string> dict = new Dictionary <string, string> (); dict ["tom"] = "Stanford"; dict ["liom"] = "galford"; dict ["lxn"] = "Harvard "; <span style = "white-space: pre"> </span> // ing code: VelocityEngine vltEngine = new VelocityEngine (); // Initialization Engine vltEngine. setProperty (RuntimeConstants. RESOURCE_LOADER, "file"); // sets the parameter. The template is located in vltEngine of the file system. setProperty (RuntimeConstants. FILE_RESOURCE_LOADER_PATH, System. web. hosting. hostingEnvironment. mapPath ("~ /Templates "); // The folder where the template is located. Map the server path to the physical path vltEngine. init (); // engine initialization <span style = "white-space: pre "> </span> // define string data string [] strs = new string [] {" Zhang San "," Li Si "," Wang Wu "}; </span> </strong>
<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <span style = "white-space: pre "> </span> // defines the generic set object data List <person> persons = new List <person> (); persons. add (new person {Name = "Li xiaona", Age = 20}); persons. add (new person {Name = "Li xiaona", Age = 20}); persons. add (new person {Name = "Li xiaona", Age = 20}); VelocityContext vltContext = new VelocityContext (); // create a context, which is the vltContext used for data transmission. put ("ps", dict); // You can reference $ data in the template. The preceding data value is vltContext. put ("minren", strs); // fill in the data and deliver the following template (test2.html) vltContext. put ("per", persons); vltContext. put ("age", 30); Template vltTemplate = vltEngine. getTemplate ("test2.html"); System. IO. stringWriter vltWriter = new System. IO. stringWriter (); vltTemplate. merge (vltContext, vltWriter); string html = vltWriter. getStringBuilder (). toString (); // The replaced html Content context. response. write (html); // directly output} public bool IsReusable {get {return false ;}}}</span> </strong>

The template html page consists of three parts:

Head html page

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <! DOCTYPE html> 

Foot html page

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <p> This website is copyrighted! $ Age </p> </body> 

Html page of the content area

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> # parse ("head.html") <! -- 1. display the defined string data --> <ul> # foreach ($ mr in $ minren) <li> $ mr </li> # end </ul> <! -- 2. traverse it through arrays and query nested conditions --> <ul> # foreach ($ p in $ per) # if ($ p. age> 20) <li style = "color: red"> $ p. the age of Name is $ p. age </li> <input type = "text" value = "$ p. name "/> </li> # else <li style =" color: green "> $ p. the age of Name is $ p. age </li> # end </ul> <! -- Condition query --> <p> # if ($ age> 10) greater than 10 # else less than or equal to 10 # end </p> # parse ("foot.html ") </span> </strong>

:


Here we use:

1. # foreach ($ element in $ list )...... This is $ element ...... # End: output the array to the interface.

2. Use the conditional statement # if (condtion )...... # Elseif (condtion )...... Else ...... # End: determines the information to be displayed based on the conditions. It can be displayed separately and embedded into traversal statements.

3. Reference external files in two ways. include does not parse external files based on the NVelocity template language, while parse parses external files based on the nVelocity template language. Note that it is better to use another annotation when using include or parse, so that the code below will not be displayed as a comment during parsing, so it is better to write one and replace the other directly.

As shown in the following figure, there is a problem with writing. Try it on your own.
<strong><span style="font-family:Microsoft YaHei;font-size:14px;"><!--#include("head.html")-->#parse("head.html")</span></strong>

Example 3: NVelocity Encapsulation

1. If a class requires a lot of data (such as entering personal information), you need to pass a lot of parameters. This is very troublesome. You can encapsulate these parameters into a class, so $ data. name, $ data. age. However, writing a class for different pages is too troublesome. in C #3.0, "Anonymous class" and varperson = new {Name = "lixiaona" are provided ", age = 25}; it is equivalent to declaring a class with two attributes: Name and Age, an instance of the new class, and declaring the variable var as "auto-inferred" with the variable, int I = person. name. the attribute is read-only.

2. When passing a able to Nvelocity, you must pass able. Rows.

3. To reduce the parsing template time, we can enable Nvelocity cache as needed.

Encapsulated instance:

General handler page:

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> using NVelocity; using NVelocity. app; using NVelocity. runtime; using System. collections. generic; using System. linq; using System. web; namespace engine {// <summary> // displayNew abstract description /// </summary> public class displayNew: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/ht Ml "; VelocityEngine vltEngine = new VelocityEngine (); // initialize the vltEngine engine. setProperty (RuntimeConstants. RESOURCE_LOADER, "file"); // sets the parameter. The template is located in vltEngine of the file system. setProperty (RuntimeConstants. FILE_RESOURCE_LOADER_PATH, System. web. hosting. hostingEnvironment. mapPath ("~ /Templates "); // The folder where the template is located. Map the server path to the physical path vltEngine. init (); // engine initialization var news = new {Title = "", Author = "lxn", PostDate = "1-1-8", msg = ""}; velocityContext vltContext = new VelocityContext (); // creates a context to transmit data using vltContext. put ("data", news); // You can reference $ data in the Template. The previous data value is the value Template vltTemplate = vltEngine. getTemplate ("displayNew.html"); System. IO. stringWriter vltWriter = new System. IO. stringWriter (); vltTemplate. merge (vltContext, vltWriter); string html = vltWriter. getStringBuilder (). toString (); // The replaced html Content context. response. write (html); // directly output} public bool IsReusable {get {return false ;}}}</span> </strong>

Html page:

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <! DOCTYPE html> 

:

Nvelocity code

The preceding three examples show the Nvelocity ing code. First, we need to introduce the namespace: using NVelocity; using NVelocity. App; usingNVelocity. Runtime;

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> // you only need to change the code when using it: template folder, add data, set template VelocityEngine vltEngine = new VelocityEngine (); vltEngine. setProperty (RuntimeConstants. RESOURCE_LOADER, "file"); vltEngine. setProperty (RuntimeConstants. FILE_RESOURCE_LOADER_PATH, System. web. hosting. hostingEnvironment. mapPath ("~ /Templates "); // folder of the template file. For example, My template is testnv.html vltEngine under the templatesfolder. init (); VelocityContext vltContext = new VelocityContext (); vltContext. put ("dataName", person); // Add data. In the template, you can use $ dataName to reference vltContext. put ("dataName2", person); // you can add multiple data types, including dictionary, Data, datatable, and other Template vltTemplate = vltEngine. getTemplate ("TestNV.html"); // sets the template System. IO. stringWriter vltWriter = new System. IO. stringWriter (); vltTemplate. merge (vltContext, vltWriter); string html = vltWriter. getStringBuilder (). toString (); context. response. write (html); // return the standard html code string generated by rendering </span> </strong>

3. Summary

Through the above examples, we have a preliminary understanding of the Nvelocity development process, that is, the running logic we mentioned earlier, if we find that the examples written here are not directly related to databases on the page, but some simple applications, we will explain the interaction with the database, continue to follow up ~




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.