dbones notes
its a geek thing

Looking into templating.

November 23, 2008 23:11 by Dave

Work in progress - published to preview

On a side project Im looking into a means of templating some output files.

I have found 2 main ways so far (with out the need of other tools such as CodeSmith) key focus is free.

  1. NVelocity (Noticed Castle Project had updated the Open Source project)
  2. TemplateMaschine (another free one, closer to T4's/ASP.NET way)

I have not included Microsoft T4 ToolBox as this seems to be for code generation, where a file will be exported to a folder.

Test

A simple road test is in order, lets look into creating the following output (consider this the HelloWorld, where the Name "Dave" can be injected as an arguement)

1. The Template File

The template file to produce this required outcome, (syntax is important, consider the people whom will write the templates, will they be coders?)

Nvolicity

Hello $Name


this is a test

TemplateMaschine

<%@ Argument Name="name" Type="string" %>
Hello <%=name%>


this is a test

First observation, the TemplateMaschine requires the varibles to be declared, this could be useful (again, it depends on what you want to do.)

2. The Code

the code samples will try to use the default settings. the template file will be located in the same folder as the created Exe.

NVolicity

With NVolicity you can set up properties on the engine, as this was more of an advance option i have left it alone.

//following the CastleProject instructions.
VelocityEngine velocity = new VelocityEngine();
ExtendedProperties props = new ExtendedProperties();
velocity.Init(props);

//get the template file.
string fileName = "<a href="file://templatefile.txt/">\\templateFile.txt</a>";
Template template = velocity.GetTemplate(fileName);

//create arguements. the context
VelocityContext context = new VelocityContext();
context.Put("Name", "Dave");

//get the output and display
StringWriter writer = new StringWriter();
template.Merge(context, writer);
Console.WriteLine(writer.GetStringBuilder().ToString());

Console.ReadLine();

TemplateMaschine

//get the execution folder.
string location =Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);


// Load a template from file 'Sample2.template' and compile it
string fileName = location + "<a href="file://template.txt/">\\template.txt</a>";
Template myTemplate = new Template(fileName);

//setup the input args
Dictionary<string,object> inputArgs = new Dictionary<string, object>();
inputArgs.Add("name", "Dave");

//get the output
string output = myTemplate.Generate(inputArgs);
Console.WriteLine(output);

Console.ReadLine();

 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags: , ,
Categories: dotNet
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts