Understanding T4: Text Blocks
Here is how T4 documentation on MSDN defines text blocks.
A text block is any non-programmatic text in a text template. You can write a text block directly to the output file of the text transformation. You can add it by simply typing the text in the text template.
You can add a text block to the generated transformation class as a Write statement. That is, you do not compile or execute the text in the generated transformation class.
Here is what happens under the hood.
Template
<#@ template language="C#" #> Hello World!
Compiled Template
using System; using Microsoft.VisualStudio.TextTemplating; namespace Microsoft.VisualStudio.TextTemplating413AE4BE2CE28AB99 { public class GeneratedTextTransformation: TextTransformation { public override string TransformText() { this.Write("Hello World!"); return this.GenerationEnvironment.ToString(); } } }
Output
Hello World!
Notice that T4 generated a concrete class called GeneratedTextTransformation, which inherits from the abstract TextTransformation. T4 used the text block from our template to generate TransformText method. Text block was turned into a string literal and passed to the Write method defined in the base class. This method appends text to the StringBuilder object exposed by the GenerationEnvironment property, which is then converted to a string and returned as template’s output.
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 statement blocks or go back to the overview.


