Understanding T4: Statement Blocks


Here is how T4 documentation on MSDN defines statement blocks.

You can use statement blocks in text templates to control the flow of processing in the text template. Statement blocks enable you either to structure templates to output things conditionally or to iterate over data to output things repeatedly for each item in that data.

Code statements are delineated using opening (<#) and closing (#>) text template tags. The general syntax is:

<# StatementCode #>

Here is what happens under the hood.

Template

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


Compiled Template

using System;
using Microsoft.VisualStudio.TextTemplating;  

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


Output

Hello World!
Hello World!
Hello World!

Notice that T4 copied contents of statement blocks to the generated TransformText code "as is", allowing us to place the opening curly brace of the for statement in first statement block, closing curly brace in the second statement block and turn the text block between them into a Write method call that will be executed inside the for loop.

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 expression 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!