Text Templates
In this post are described text templates. It was used in the developed tool. With it you can generate source code for modeled functional programs. The user has two choices: it can either use the default templates provided with the plugin, or define your own templates.
Text Templates in Microsoft Visual Studio 2010 are elements in which you can place blocks of text together with control logic generating other text files.
In this post are sample template files .tt used to generate source code files from models built by using the DSL Tools.
The following Listing 1 is shown a text template used in this plugin. In this template is called the method GenerateCode (), which puts the source code in the space between the markers shown in the listing
<#@ output extension=".fs" #> <#@ VisualModelForFSharp processor="VisualModelForFSharpDirectiveProcessor" requires="fileName='$fileinputname$.vmffs'" #> <#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #> //plugin: Visual Model For F# //author: Adam Bielasty //website: www.bielasty.pl <#= this.RootModel.GenerateCode() #>
Listing 1: Text Template used in the project
Method GenerateCode() indirectly calls other methods, they include:
- GenerateCodeForAttribute(Attribute a, int offset)
- GenerateCodeForFunction(Function f, int offset)
- GenerateCodeForMethod(Operation o, int offset)
- GenerateCodeForModule(Module m, int offset)
- GenerateCodeForOperation(Operation o, int offset)
- GenerateCodeForProperty(Operation o, int offset)
- GenerateCodeForType(TypeElement t, int offset)
- and other auxiliary methods
The parameter offset determines the length of indentation in the code.
Methods were created for this tool. With their help, you can define your own logic to generate source code in these templates.
An example would be the template below in Listing 2
<#@ output extension=".fs" #> <#@ VisualModelForFSharp processor="VisualModelForFSharpDirectiveProcessor" requires="fileName='$fileinputname$.vmffs'" #> <#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #> //plugin: Visual Model For F# //author: Adam Bielasty //website: www.bielasty.pl //Text template generates source code only for classes <# foreach (TypeElement te in this.RootModel.SubElements) { #> //another class <#= this.RootModel.GenerateCodeForType(te, 0) #> //to do... <# } #>
Listing 2: The text template that generates code only for classes
It is a useful mechanism that provides greater flexibility in generating the source code. The user can thus define any number of ancillary text templates.