Home > Templates > The Text Template Engine

The Text Template Engine

CodeFluent Entities provides a text template engine which you can use at:

  • production time: to generate configuration files, documentation, extra sources, or any text files you might need
  • run time: use the template engine in your own application to generate invoices, reports, or whatever you might need based on templates.

Here’s a sample CodeFluent text template:

This is a template sample:
Hello [%=Name%]!!

Note the ASP.NET like [%= expression %] to print an expression value. Likewise, you can also write C# statements such as: [% my statements %].

Here’s a code snippet which uses this template to generate a text file at runtime:

using System;
using System.Collections;
using System.IO;
using CodeFluent.Model.Common.Templating;

namespace TemplateEngineSample
    class Program
        static void Main(string[] args)
             if (args.Length != 1)
                Console.WriteLine("Template file must be specified!");

            string templateFilePath = args[0];
            Template template = new Template();
            template.Load(templateFilePath, TemplateOptions.Default);

            template.AddParameterDirective("Name", typeof(string));

            using (FileStream fs = new FileStream("Result.txt", FileMode.Create))
                using (StreamWriter writer = new StreamWriter(fs))
                    Hashtable parameters = new Hashtable();
                    parameters.Add("Name", "CodeFluentees");
                    template.Run(writer, parameters);

Running this code by specifying our template as parameter will create a Result.txt file with the following content:

This is a template sample:
Hello CodeFluentees!!

Since those templates are outside of your compiled code, as long as you don’t need extra parameters in them, you can actually change them as much as you’d like without having to compile and deploy over your application. Therefore, if your accounting department wants a new layout for the generated invoices; all you have to do is update the invoice template used by your application!

Categories: Templates Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s