Understanding T4: Expression Blocks


Here is how T4 documentation on MSDN defines expression blocks.

You can use expression blocks in text templates to add strings to the generated text output. Expression blocks contain code that is first added to the generated transformation class with calls to ToString() attached to them. The transformation process will also apply the template’s culture to the generated string. Typically, expression blocks are embedded inside text blocks. They are designed to change some aspect of the generated output text to use calculated values from external data, such as model files.

In text templates, expression blocks are delineated by using opening (<#=) and closing (#>) text template tags. The general syntax is:

<#= ExpressionCode #>

Here is what happens under the hood.

Template

<#@ template language="C#" #>
<#
    for(int i = 1; i <= 3; i++)
    {
#>
Hello World <#= i #>!
<#
    }
#>


Compiled Template

using System;
using Microsoft.VisualStudio.TextTemplating;  

namespace Microsoft.VisualStudio.TextTemplating76E036EA7C70CB236
{
   public class GeneratedTextTransformation: TextTransformation
   {
      public override string TransformText()
      {
         for (int i = 1; i <= 3; i++)
         {
            this.Write("Hello World ");
            this.Write(ToStringHelper.ToStringWithCulture(i));
            this.Write("!\r\n");
         }
         return this.GenerationEnvironment.ToString();
       }
   }
}


Output

Hello World 1!
Hello World 2!
Hello World 3!

In this template, we are using an expression block to write value of a local variable (i) to the output file. Notice that T4 converted the expression block into a call to ToStringWithCulture method and passed its result to the Write method of TextTransformation. Although the same task could be accomplished using a statement block that calls the Write method explicitly, expression block syntax is more concise.

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.

Ready for more? Read about class feature blocks or go back to the overview.


Write a Comment

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

Reader Comments

Be the first to leave a comment!