Message Templates with T4 and C# Partial Classes
You could be wasting a couple of hours figuring out how to generate text templates using T4 and C#. In this post I quickly show you how to do that.
End Result
A very good example of generating texts using a few input parameters, is to send an email. The process to generate such text should be very simple however, to keep it separate from the email generation logic.
If you look at the below line, I just have a class, pass a bunch of parameters, call TransformText function, and here I have the final transformed text:
- Create T4 Template
The first step is to generate the right T4 template when you try to add a new item. From the three available templates, make sure you choose Runtime Text Template.
2. Set Custom Tool
Once generated, go to the file properties for the T4 template and set the custom tool to TextTemplatingFilePreprocessor from the default value.
3. Create Template
Next is to create your template, i.e. the final text + all the placeholders to be replaced with the real values at run time. The placeholder actually belongs to an object, called Model, which I will cover a bit later.
As you might notice, the moment we save this file, a C# file with the same name gets generated, which contains all the logic to handle the templating. There is one specific method there that we have used called TransformText, it is auto-generated and you shouldn’t modify that, as it will cause random behavior and will be discarded the next time you press save on the .tt file.
4. Replace the Placeholders
Now the final and most important step is to replace the placeholders in the tt file, in this case Name. If you look at the final state below, we are passing the arguments using a class constructor with the same name as the tt template file:
However the the generated cs class doesn’t provide that constructor, and doesn’t have any object named Model. So where did that object come from?
4.1 Partial Class
The answer is the partial class that we create manually exactly for that purpose. In this class we have included the Model object, and it contains the properties, Name, used in the template.
4.2 Files Structure
As you might have lots of these templates, and to make your structure maintainable, I’d suggest to create a folder for each. In doing so however, make sure the name of your partial C# class file is different, so you could keep them in the same folder. Please note, the name of the class still stay the same as the tt template, and it is just the physical file name which is different.
5. Putting it all Together
At the end, creating an object of your partial class, and calling TransformText, will generate the final desired output: