T 4 beginners – part 3


no comments

T 4 beginners – part 3

T4, VS 2010, Entity Framework, Custom tool

this is the 3rd post on this series.

in this post we will focus on basics T4 Control blocks.

you can download the code sample from here.

the series TOC is available here.


T4 Control blocks is where dynamic text is added into the template output,

this is the heart of T4 concept

(C# is the default language but you can change it to VB).


Standard control blocks

A standard control block is a section of program code that generates part of the output.

You can mix any number of text blocks and standard control blocks in a template file.

However, you cannot place one control block inside another.

Each standard control block is delimited by the symbols <##>.


Code Snippet
  1. /*
  2. *  generate on <# WriteLine(DateTime.Now.DayOfWeek.ToString()); #>
  3. */

the above snippet include control block that write the current day of week.

this is the code it generate:

Code Snippet
  1. /*
  2. *  generate on Friday
  3. */


Expression control blocks

An expression control block evaluates an expression and converts it to a string and insert it into the output file.

the syntax of expression control blocks is using the <#= #> syntax instead of <# #> .

Code Snippet
  1. /*
  2. *  generate on <#= DateTime.Now.DayOfWeek.ToString() #>
  3. */

both the WriteLine and the ; were omit.


the following snippets is using expression control block combine with standard control block which

use for iterations:

Code Snippet
  1.  <#
  2. for(int i = 0; i < 4; i++)
  3. {
  4.  #>
  5.      // This is hello number <#= i+1 #>: Hello!
  6.  <#
  7.  }
  8.  #>

lines 1-3, start the iterations.

line 5, write text block which embedded expression control block that write the current iteration count.

lines 6-8, close the iterations.

the output will look like:

Code Snippet
  1. // This is hello number 1: Hello!
  2. // This is hello number 2: Hello!
  3. // This is hello number 3: Hello!
  4. // This is hello number 4: Hello!



the control block is what T4 is doing, create dynamic section


kick it on DotNetKicks.com Shout it

Digg This
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>