Early T4 template experience (syntax)

Source: Internet
Author: User

I. What is a T4 template?

T4 is the abbreviation of the four initials of Text Template transformation Toolkit (Text Template conversion Toolkit. Is a code generation engine provided by Microsoft.

In ADO. NET Entity Data Model and EF framework, the code automatically generated according to the database table structure is generated according to this engine, therefore, when we are not satisfied with the code automatically generated by vs or have special requirements, we can modify the T4 template to achieve our goal.

In vs2012, you can add a T4 template (with. tt as the suffix) by following the steps below ):

"Text Template" and "RunTime Text Template" are two types of T4 templates provided by Microsoft.

When a "Text Template" is added, the following code is generated by default in the new file:

<# @ Template DEBUG = "false" hostspecific = "false" Language = "C #" #>
<# @ Assembly name = "system. Core" #>
<# @ Import namespace = "system. LINQ" #>
<# @ Import namespace = "system. Text" #>
<# @ Import namespace = "system. Collections. Generic" #>
<# @ Output extension = ". txt" #>

2. Compile a T4 Text Template-syntax

To learn how to write a T4 template, you must first understand the syntax of the T4 template.

A text template consists of the following three parts:

  • Instructions for Text Template conversion Engine
  • Text block: Output content
  • Control Block: inserts program code such as variables or loops into text blocks.

2.1 commands

Commands are usually the first element in a template or include file. The syntax is as follows: <# @ command name [attribute name = "attribute value"]… #>

The t4 template contains the following commands: Template instruction, output instruction, parameter instruction, assembly instruction, import instruction, and include instruction.

  • Template instructions

The general format of template commands is as follows:

<# @ Template [Language = "VB"] [hostspecific = "True | truefrombase"] [DEBUG = "true"] [inherits = "templatebaseclass"] [culture = "code"] [compileroptions = "options"] [visibility = "internal"] [linepragmas = "false"] #> all attributes of the template command are shown above, these commands specify different aspects of conversion and are optional.LanguageAttributeValid values: C # (default) and VB. Specifies the programming language used by the program code in the template.Hostspecific attributes: Valid values: True, false (default), truefrombase.

If it is set to true, the property named host is added to the class generated by the text template. This property is a reference to the host of the conversion engine and declared as itexttemplatingenginehost.
If you have defined a custom host, you can convert it to a custom host type. (For more information about itexttemplatingenginehost, see:
http://msdn.microsoft.com/zh-cn/library/vstudio/microsoft.visualstudio.texttemplating.itexttemplatingenginehost(v=vs.110).aspx
)

Debug attributes: Valid values: true and false (default)

If the DEBUG feature is true, the intermediate code file contains information that enables the debugger to more accurately identify the location where the template is interrupted or abnormal. For the design-time template, the intermediate code file will be written to your % Temp % directory.

Inherits attributes:

The program code of the specified template can inherit from another class, which can also be generated from the Text Template.

  • Parameter commands

The parameter command declares the attributes of the value initialized from the external context in the template code. Basic Syntax: <# @ parameter type = "full. typename" name = "parametername" #>

For example, <# @ template Language = "C #" #> <# @ parameter type = "system. int32 "name =" timestorepeat "#>< # For (INT I = 0; I <timestorepeat; I ++) {#> line <#= I #><#}#>

  • Output command

The output command defines the file extension and encoding of the converted file. Basic Syntax: <# @ output extension = ". filenameextension" [encoding = "encoding"] #>

Note: Each text template should not contain multiple outputs. The default extension value is ". cs", for example, <# @ output extension = ". txt" #>

  • Assembly instructions

The Assembly command can load the Assembly so that your template code can use its type. This function is similar to adding an Assembly reference in a Visual Studio project.

Basic Syntax: <# @ Assembly name = "[Assembly strong name | assembly file name]" #> the Assembly name must comply with the following specifications:

The strong name of the Assembly in GAC, such as system. xml. dll. You can also use the long format, such as name = "system. XML, version = 4.0.0.0, culture = neutral, publickeytoken = b77a5c561934e089 ".

Absolute path of the Assembly

  • Import command

The import command allows you to reference elements in another namespace without providing a fully qualified name, which is equivalent to using in C #.

Basic Syntax: <# @ import namespace = "namespace" #>

Example: <# @ import namespace = "system. Io" #>

Note: The system namespace will be automatically imported

  • Include commands

You can use the <# @ include #> command to include text from another file. Basic Syntax: <# @ include file = "filepath" [once = "true"] #>

Filepath can be an absolute path or a path relative to the template

2.2 Control Block

  • Standard Control Block

Controls the output file content. Included in <#... #> Marking

For example:

<# @ Template DEBUG = "false" hostspecific = "false" Language = "C #" #>
<# @ Output extension = ". txt" #>

<#
Int Top = 10;
For (INT I = 0; I <= top; I ++)
{
#>
The square of <# = I #> is <# = I * I #>
<#
}
#>

The output is as follows:

The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100

  • Expression Block

Expression control block is used to provide the code of the string to be written into the output file, and for the output of variable values. Expression block placed in <# =... #> Marking

For example:

The square of <# = I #> is <# = I * I #> outputs the I value and the I * I value.

  • Class Function Control Block

You can use the class function control block to add methods, attributes, fields, and even Nested classes to a text template. The class function block is most commonly used to provide helper functions for the code of other components in the Text Template. Put in <# +... #> Tag, which must be placed at the end of the template.

For example:

<# + Private int doublenumber (INT number) {return 2 * number;} #>

The double of <# = I #> is <# = doublenumber (I) #>

Note: The above three tags cannot be nested with each other. Only one tag can be completed and the first tag can be enabled.

2.3 text blocks

Does not contain text with any identifier, such as: This is the content.

2.4 tool methods in text templates

  • Write Method

The write () and writeline () Methods append text to the standard code block without using the expression code block.

For example, the following two code blocks

Code using expression block <# int I = 10; while (I --> 0) {#>< # = I #>< #}#>

Code block using writeline ()

<# Int I = 10; while (I --> 0) {writeline (I. tostring ();} #>

  • Indent Method

The pushindent () method increases indentation; The popindent () method reduces indentation; and The clearindent () method deletes all indentation.

  • Error and warning methods

Error () method outputs error information; warning () method outputs warning information. For example: <# Try {string STR = NULL; write (Str. length. tostring ();} catch (exception e) {error (E. Message);} #>2.5 others

Command name

Parameter description

Function

$ (Projectname)

Basic Project Name

Obtain the path of a specified project

$ (Solutionname)

Solution name

Obtain the path of the given Solution

 

Early T4 template experience (syntax)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.