Preprocessed T4 Templates

A preprocessed T4 template is an easy, out-of-the-box technology you can use for generating text from a template at runtime. Preprocessed templates are a little different than the T4 templates you might have used in the past. For details, read Oleg Sych's post on the topic

As an example, let's say you add a preprocessed template named "LetterTemplate.tt" to a project, with the following content:

<#@ template language="C#" #>

Hi <#=  Model.FirstName  #>,

Thank you for the email. Although our schedules 
are very busy, we decided to take some time and 
write you a personal reply. 

We appreciate the thoughtful feedback on 
show <#= Model.ShowNumber #>, and we want to promise 
you, <#= Model.FirstName #>, that we will try harder. 

Sincerely, 

For this example, only three pieces of code are required. First there is the partial class to extend the definition of a class generated from the template:

public partial class LetterTemplate
{
    public LetterModel Model { get; set; }
}

Secondly is the definition of LetterModel:

public class LetterModel
{
    public string FirstName { get; set; }
    public string ShowNumber { get; set; }
}

And finally, only a few lines of code are required to execute the template and produce a result.

var template = new LetterTemplate();
template.Model = new LetterModel()
{
    FirstName = "...",
    ShowNumber = "..."
};
var message = template.TransformText();

TranformText is all you need , yet the generation scenarios can be much more complex.

Print | posted @ Tuesday, January 04, 2011 9:12 AM

Comments on this entry:

Gravatar # re: Preprocessed T4 Templates
by tobi at 1/5/2011 9:13 AM

How cool is that?
  
Gravatar # re: Preprocessed T4 Templates
by Aaron at 1/5/2011 8:14 PM

Effin' sweet!

Goodbye, long-winded stringbuilder joins and string.Format statements.

You rock, thanks!
  
Gravatar # re: Preprocessed T4 Templates
by Marco Rizzi at 1/6/2011 6:32 AM

What about processing effort? Did you executed any benchmark?
  
Gravatar # re: Preprocessed T4 Templates
by scott at 1/6/2011 10:50 AM

@Aaron - exactly!

@Marco - I haven't benchmarked, no.
  
Comments have been closed on this topic.
Scott Allen
Posts - 869
Comments - 4493
Stories - 14