http://www.castleproject.org/others/nvelocity/usingit.html#step1
Using NVelocity
This is a very basic instruction on getting NVelocity working. Basically you need an engine instance and one or more templates. The result of the process is known as the merge of the template with a context (ie the data).
For simplicity's sake, we will use e-mail template as example.
Step 1 - Creating a VelocityEngine
First you must have an engine instance. You can initialize an instance with several properties that dictate the NVelocity behavior regarding encoding, cache and other things.
using Commons.Collections; using NVelocity; using NVelocity.App; using NVelocity.Context; ... VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); velocity.Init(props);
Step 2 - Creating the Template
The template is created by the engine from a file. Assuming that we are producing an e-mail template, let's create something simple:
From: $from To: $to Subject: $subject Hello $customer.Name We're please to yada yada yada.
Save the content above to a file and use its absolute path in the line below in your C# code:
Template template = velocity.GetTemplate(@"path/to/myfirsttemplate.vm");
Step 3 - Merging the template
Merging is the process of combining the data with the template instructions to create the resulting content. You make data available to the template using a context.
VelocityContext context = new VelocityContext(); context.Put("from", "somewhere"); context.Put("to", "someone"); context.Put("subject", "Welcome to NVelocity"); context.Put("customer", new Customer("John Doe") );
Finally create a writer to output the content. The code below uses simply a StringWriter:
StringWriter writer = new StringWriter(); template.Merge(context, writer); Console.WriteLine(writer.GetStringBuilder().ToString());
You see the merged result in the console if you used the code above.