Summary of several NVelocity-based content generation methods and several nvelocity

Source: Internet
Author: User

Summary of several NVelocity-based content generation methods and several nvelocity

I have been using NVelocity for several years, mainly using my code generation tool Database2Sharp to generate relevant Code. However, NVelocity is a very good template engine, it can be used to generate files, pages, and other related processing, which is very efficient and convenient.

It was originally maintained on the site http://nvelocity.sourceforge.net/, but since 0.41, the site no longer performs NVelocity updates, now you can.

1. Several NVelocity-based content generation methods

As shown in the preceding figure, NVelocity templated generation includes three methods: one is from file to file or string, and the other is from string to string, their respective processing methods are different, but they can correctly parse the content.

To better utilize NVelocity features, we provide a preliminary helper class encapsulation for it.

/// <Summary> /// the auxiliary class generated based on the NVelocity Template file /// </summary> public class NVelocityHelper {protected VelocityContext context; protected template Template; protected string templateFile; /// <summary> /// Dictionary content for storing key values /// </summary> private Dictionary <string, object> KeyObjDict = new Dictionary <string, object> (); // <summary> // Add a key-value object // </summary> // <param name = "key">, 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 above AddKeyValue method is mainly used to add variable objects to be bound to the template engine on the page, so that the content of the page variable parameters can be correctly parsed.

To use various NVelocity features, we need to construct information about the template in the helper class and set relevant parameters.

/// <Summary> /// initialize the 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 attribute is set, the basic path of the template file is the directory based on this setting; otherwise, the current running directory is templateEngine by default. 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 generating the content, you need to bind the relevant object attributes to the context object of the template engine.

/// <Summary> /// initialize the context content /// </summary> private void InitContext () {context = new VelocityContext (); foreach (string key in KeyObjDict. keys) {context. put (key, KeyObjDict [key]) ;}}

1) construct the corresponding file content based on the template file

/// <Summary> /// create an output file based on the template and return 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 the template file

/// <Summary> /// output string content based on the template /// </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> /// merge string content /// </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 calling code of the preceding operation templates is as follows.

Private void btnGenerateFile_Click (object sender, EventArgs e) {string tempalte = "Template/template.htm"; // relative directory TestInfo info = new TestInfo (); info. title = "test Title"; info. content = "Test Content, 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. da TeTime. 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 info = new TestInfo (); info. title = "test Title"; info. content = "Test Content, 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", infotrans extends this.txt Code. text = adapter. executeString ();} private void btnMergeString_Click (object sender, EventArgs e) {System. text. stringBuilder builder = new System. text. stringBuilder (); 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", "Title "). addKeyValue ("Content", "Content "). addKeyValue ("Digest", "abstract "). addKeyValue ("Author", "Author "). addKeyValue ("Keyword", "Keyword "). addKeyValue ("DateTime", datetime.now?#this.txt Code. text = adapter. executeMergeString (builder. toString ());}

2. Application scenarios of the template engine NVelocity

The methods of the preceding template content can meet our application requirements in most cases. For example, you can define custom content templates in the code generation tool, then, it can combine the metadata information of the database to generate code with rich logic.

You can also use content management applications (such as document management) to generate files of the document content based on the input content, we can simply use the file link address of the article.

You can also generate a specific page based on the data information for the set-up operation. The following is the set-up processing in Winform.

The above is a summary of several NVelocity-based content generation methods. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.