Meeting the needs of your business from a distance

Preprocessed T4 Templates

by mark shiffer 26. January 2011 21:28

K. Scott Allen recently had a post on Preprocessed T4 Templates  that has a nifty little trick. You can use a preprocessed T4 template to generate mail-merge like text via code. Essentially all you do is define your text in a preprocessed T4 template and use syntax like “<#=  Model.FirstName  #>” in the text for fields to fill in. The trick is extending the template via a partial class that defines the Model variable. Then all that is necessary is to new up the template in code and call TransformText on it. Pretty cool trick that I hadn’t thought of. Actually I didn’t even realize that preprocessed templates existed. I’ve used T4’s before but didn’t now about this separate type.

Another article linked from the one above goes into greater detail on preprocessed templates. It was done by Oleg Sych and is called Understanding T4: Preprocessed Text Templates.  Worth checking out if you are interested in this sort of thing.

Here is the example that K Scott Allen gave:

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();

Tags:

Comments

Add comment


(Will show your Gravatar icon)

  Country flag


  • Comment
  • Preview
Loading



Copyright © 2001-2012 MS Consulting, Inc. All Rights Reserved.