Summary of several content generation methods based on nvelocity-practical skills

Source: Internet
Author: User
Tags datetime

The use of nvelocity is also a few years, mainly in my Code generation tool Database2sharp used to generate the relevant code, but nvelocity is a very good template engine, can be used to generate files, pages and other related processing, very efficient and convenient.

It was originally maintained on the site http://nvelocity.sourceforge.net/, but since 0.41, the site is no longer nvelocity update, can now be on the site http://nvelocity.codeplex.com /To get the latest version of the update, and then the version of the update operation, we will nvelocity several of the operation of the file to introduce, so that we have a more in-depth understanding.

1. Several content generation methods based on nvelocity

From the above illustration, we can see that the templating generation of Nvelocity contains 3 ways, one is from file to file or string, one is from string to string, they are handled differently, but they can parse the contents correctly.

In order to make better use of nvelocity features, we have a preliminary auxiliary class encapsulation.

<summary>
///nvelocity-based template file generation auxiliary class
///</summary> public
class Nvelocityhelper
{
protected Velocitycontext context;
protected Template Template;
protected string templatefile;
<summary>
///The contents of the dictionary containing key values
///</summary>
private dictionary<string, object> Keyobjdict = new dictionary<string, object> ();
<summary>
///Add a key value object
///</summary>
///<param name= "key" > key, not repeatable </param >
///<param name= "value" > Value </param>
///<returns></returns>
Public Nvelocityhelper Addkeyvalue (String key, object value)
{
if (! Keyobjdict.containskey (key))
{
Keyobjdict.add (key, value);
}
return this;
} ................

The Addkeyvalue method above is mainly used to add some variable objects that need to be bound on the page for the template engine so that the contents of the page variable parameters can be parsed correctly.

In order to use the various features of nvelocity, we need to construct the relevant information of the template in the auxiliary class, and set the relevant parameters.

<summary>///initialization template engine///</summary> protected virtual void Inittemplateengine () {try {//velocity.init (
Nvelocity_property);
Velocityengine templateengine = new Velocityengine ();
Templateengine.setproperty (Runtimeconstants.resource_loader, "file");
Templateengine.setproperty (runtimeconstants.input_encoding, "utf-8");
Templateengine.setproperty (runtimeconstants.output_encoding, "utf-8"); If the File_resource_loader_path property is set, the base path of the template file is the directory based on this setting, or the default current run directory Templateengine.setproperty (
Runtimeconstants.file_resource_loader_path, AppDomain.CurrentDomain.BaseDirectory);
Templateengine.init ();
Template = Templateengine.gettemplate (templatefile); catch (Resourcenotfoundexception re) {string error = string.
Format ("Cannot find template" + templatefile);
Logtexthelper.error (Error);
throw new Exception (error, re); catch (Parseerrorexception pee) {string error = string. Format ("Syntax Error in Template" + TemplateFile + ":" + pee.
StackTrace);
Logtexthelper.error (Error); ThroW New Exception (Error, pee); }
}

Before you generate the content, you need to bind the related object properties to the context object of the template engine.

<summary>
///The contents of the initialization context
///</summary>
private void Initcontext ()
{Contextual
= new Velocitycontext ();
foreach (string key in Keyobjdict.keys)
{context
. Put (key, Keyobjdict[key]);
}

1 According to the template file to construct the corresponding file content

<summary>
///creates the output file based on the template and returns the generated file path
///</summary> public
virtual String executefile ()
{
String fileName = ' ";
if (template!= null)
{
string filePath = Checkendbyslash (directoryofoutput);
FileName = FilePath + filenameofoutput + fileextension;
if (!string. IsNullOrEmpty (FilePath) &&! Directory.Exists (FilePath))
{
directory.createdirectory (filePath);
}
Logtexthelper.debug (String. Format ("Class file Output path:{0}", FileName));
Initcontext ();
using (StreamWriter writer = new StreamWriter (FileName, False))
{
template. Merge (context, writer);
}
}
return fileName;
}

2 construct string content based on template file

<summary>
///based on template output string content
///</summary>
///<param name= "TemplateFile" ></ param>
///<returns></returns> public
string executestring ()
{
initcontext (); 
System.IO.StringWriter writer = new System.IO.StringWriter ();
Template. Merge (context, writer);
return writer. Getstringbuilder (). ToString ();
}

3 construct string output based on string content

<summary>
///The contents of the merged strings
///</summary>
///<returns></returns>
public string executemergestring (string inputstring)
{
Velocityengine templateengine = new Velocityengine () ;
Templateengine.init ();
Initcontext ();
System.IO.StringWriter writer = new System.IO.StringWriter ();
Templateengine.evaluate (context, writer, "MyString", inputstring);
return writer. Getstringbuilder (). ToString ();
}

The above several modes of operation template output, the calling code is shown below.

private void Btngeneratefile_click (object sender, EventArgs e) {string tempalte = "template/template.htm";//Relative directory Testinf
o info = new TestInfo (); Info.
title = "Test title"; Info.
Content = "Test contents, this is the test content"; Info.
Datetime = DateTime.Now;
Nvelocityhelper adapter = new Nvelocityhelper (tempalte); Adapter. Addkeyvalue ("title", "This is a title"). Addkeyvalue ("Content", "This is a content"). Addkeyvalue ("datetime", System.DateTime.Now).
Addkeyvalue ("TestInfo", info); Adapter.
Filenameofoutput = "Testtemplate"; String FilePath = adapter.
Executefile (); if (!string. 
IsNullOrEmpty (FilePath)) {Process.Start (FilePath);}} private void Btngenerate_click (object sender, EventArgs e) {string tempalte = "template/template.htm";//Relative directory TestInfo inf
o = new TestInfo (); Info.
title = "Test title"; Info.
Content = "Test contents, this is the test content"; Info.
Datetime = DateTime.Now;
Nvelocityhelper adapter = new Nvelocityhelper (tempalte); Adapter. Addkeyvalue ("title", "This is a title"). Addkeyvalue ("Content", "This is a content"). Addkeyvalue ("dateTime ", System.DateTime.Now).
Addkeyvalue ("TestInfo", info); This.txtCode.Text = adapter.
Executestring (); } private void Btnmergestring_click (object sender, EventArgs e) {System.Text.StringBuilder builder = new System.Text.Str
Ingbuilder (); Builder.
Append ("${title}\r\n" + "$Content \ r \ n" + "$Digest \ r \ n" + "$Author \ r \ n" + "$Keyword \ r \ n" + "$DateTime \ r \ n");
Nvelocityhelper adapter = new Nvelocityhelper (); Adapter.
Addkeyvalue ("title", "caption").
Addkeyvalue ("Content", "contents").
Addkeyvalue ("Digest", "Summary").
Addkeyvalue ("Author", "author").
Addkeyvalue ("Keyword", "keywords").
Addkeyvalue ("DateTime", DateTime.Now); This.txtCode.Text = adapter. Executemergestring (builder.
ToString ()); }

2. Several application scenarios of template engine nvelocity

The above several ways of manipulating template content, in most cases, can meet our application requirements, such as in the Code generation tool, define some custom content templates, and then combined with the database metadata information, to achieve rich logic code generation operations.

Also can be in some content management application (such as article management aspect), according to the input content, realizes the article content the file generation operation, after this generation, we directly use the article the file link address to be possible.

or according to the data to generate a specific page, used to set the operation, the following is WinForm inside the Set dozen processing.

The above is a small set for you to introduce a number of content based on nvelocity based on the collection of several ways, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.