OdeToCode IC Logo

Preprocessed T4 Templates

Tuesday, January 4, 2011

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. 


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.