Template engine (NVelocity) development, template nvelocity
Using templates for development in net and a large amount of html code in handler. To solve this problem, I can use the template engine (NVelocity) for development.
1. First, put the NVelocity. dll file into the project, and then reference it.
2. configuration change,
The Code is as follows:
Context. response. contentType = "text/html"; // 1. create a Velocity engine and set the attribute VelocityEngine vltEngine = new VelocityEngine (); vltEngine. setProperty (RuntimeConstants. RESOURCE_LOADER, "file"); vltEngine. setProperty (RuntimeConstants. FILE_RESOURCE_LOADER_PATH, context. request. mapPath ("~ /Templates "); vltEngine. init (); // 2. velocity context object settings VelocityContext vltContext = new VelocityContext (); vltContext. put ("data", "yhb"); // 3. create Template vltTemplate = vltEngine. getTemplate ("photo.htm"); System. IO. stringWriter vltWriter = new System. IO. stringWriter (); // 4. merge the template and context object and output the vltTemplate. merge (vltContext, vltWriter); context. response. write (vltWriter. getStringBuilder (). toString ());
Change the required part of the above Code to the configuration I need. the path put in the MapPath is the path of htm, 2. vltContext. put as a key-value pair in the Put method. The value is the desired information, such as datateble and list. vltEngine. put in the GetTemplate method as the currently used template htm. (File) is read as a file.
3. Use of the front-end,
The front-end code is as follows:
<Head> <title> use of the template engine </title> <style type = "text/css"> img {width: 50px; height: 50px;} table {border: 1px solid black; border-collapse: collapse;} table th, table td {border: 1px solid black ;} </style>
Note that $ is a medium syntax in the code, followed by vltContext. the key of the key-value pair set in Put can access data. In NVelocity, only the foreach loop is available. When the loop starts, use # end when the foreach ends.
$ The key is set to a value. If this value is not set, the original style is displayed on the page, and the reverse type is used ($! Key.
When $! After the key is directly followed by an English letter, NVelocity will talk about this access as a non-existent key access. In this case, you can use $! {Key} xiaoxue syntax access.