Before reading this article, I would recommend reading the following previous parts:
In the previous articles, we looked into runtime/preprocessed templates and passed the parameters to it. Let’s drill down more and understand how to reuse a template and debug it. We can re-use an existing template using the Include directive. This will allow us to share the template code and boilerplate text between templates.
<#@ include file="filePath" [once="true"] #>
Here, the file path can be absolute or relative to the current template file and can have any extension. If you include the file’s extension as .tt, Visual Studio sets its custom tool property to TextTemplatingFileGenerator. You do not usually want included files to be transformed individually. Hence, it is recommended to use a different extension apart from .tt to include the templates.
Setting once="true" will ensure that a template is included only once, even if it’s invoked from more than one, including the other file.
We can keep include directive anywhere inside the text template before the first class feature block <#+ ... #>.
Let’s add the two templates to our project and understand it.
Let’s add a method to include the template.
Let’s include in the main template, using include directive and re-use Template1 method, defined in included template.
Output
Here, we reused a template using Include directive.
We can re-use methods, defined in an assembly by using an assembly and importing the directives.
Let’s create a sample class library with the class given below and use it in our template.
Here, we defined a method GetEmpName() to return emp name, used $ to substitute Name property with its value(Emp 1) and surrounded Name with {} to treat it as a property name, instead of text.
Let’s include this dll in our template.
Output
We can use escape sequences to include the template tags like <#, control characters and quotation marks in a text block using \, as shown below:
Output
We can debug a template by creating a breakpoint inside it then right-clicking on it and clicking on Debug T4 template in Solution Explorer,
T4 templates are helpful in defining Domain-Specific Language, and in code generation, and are used in the entity framework and MVC scaffolding templates.
I am ending the things here on T4 templates. I hope this article will be helpful for all.