T4 Template Design: Template Method


Template Method is one of T4 template design techniques that can be used to develop reusable templates. It encapsulates the main template as a method in a class feature block. Template parameters are defined as parameters of the method. The calling template uses an include directive to merge code of the template method with the code of the calling template and calls the method from a statement block.

Main Template

<#+
    void GenerateClass(string className)
    {
#>
public class <#= className #>
{
    <#+ WritePropertyAttributes(); #>
    public string Property
    {
        get { return _property; }
        set { _property = value; }
    }
}
<#+
    }
#>

Calling Template

<#@template language="C#"#>
<#
    GenerateClass("TestClass");
#>
<#@include file="Template.tt"#>
<#+
    void WritePropertyAttributes()
    {
#>
[DataMember]
<#+
    }
#>

Output

public class TestClass
{
    [DataMember]
    public string Property
    {
        get { return _property; }
        set { _property = value; }
    }
}

How It Works

The main template completely encapsulates code generation in a single method defined in a class feature block. Parameters of this method provide all information required to generate the required output. In the example above, GenerateClass is a template method that requires a single parameter - className. The calling template merges with the main template with an include directive and calls the template method from a statement block.

The main template defines extension points by calling predefined methods, which have to be implemented in the calling template. In the example above, WritePropertyAttributes method serves as an extension mechanism that allows template user to provide custom attributes for the property generated by the main template.

Here is what the calling template looks like when compiled by T4.

using System;
using Microsoft.VisualStudio.TextTemplating;

namespace Microsoft.VisualStudio.TextTemplatingEF09136258E2E4ED
{
  public class GeneratedTextTransformation: TextTransformation
  {
    public override string TransformText()
    {
      GenerateClass("TestClass");
      return this.GenerationEnvironment.ToString();
    }

    void WritePropertyAttributes()
    {
      this.Write("[DataMember]\r\n");
    }

    void GenerateClass(string className)
    {
      this.Write("public class ");
      this.Write(ToStringHelper.ToStringWithCulture(className));
      this.Write("\r\n{\r\n\t");
      WritePropertyAttributes();
      this.Write("\tpublic string Property\r\n\t{\r\n\t\t" +
          "get { return _property; }\r\n\t\t" +
          "set { _property = value; }\r\n\t}\r\n}\r\n");
    }
  }
}

Pros

This technique allows to parameterize a one-off template and reuse it to generate multiple artifacts of the same type. It also allows to extend the main template in the calling template without resorting to modification of the main template itself.

Compared to Merged Template Class, this technique provides better encapsulation for the main template by placing it inside a single method and not relying on the order of statement and text blocks to work correctly. This technique also defines an explicit interface between the main template and the calling template in the form of the method declaration.

This technique allows to compose templates. In other words, you can use multiple templates to generate multiple outputs from a single calling template by saving accumulated output.

Cons

This technique doesn’t define an explicit extensibility interface. Template user must understand which extension methods the main template requires in order to implement them correctly. Adding a new extension method to the main template breaks the already implemented calling templates by introducing a call to a non-existent method.

As the complexity of the main template increases and the number of its parameter grows, it becomes more and more difficult to use because all of the template parameters are packed into the parameter list of a single method.

About T4

T4 (Text Template Transformation Toolkit) is a template-based code generation engine. It is available in Visual Studio 2008 and as a download in DSL and GAT toolkits for Visual Studio 2005. T4 engine allows you to use ASP.NET-like template syntax to generate C#, T-SQL, XML or any other text files.

For more information about T4, check out my previous article.


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

[…] in the template structure and indented in order to output the tag exactly where it should be. Using this technique the method can be shared with other text […]