How to: Add Helper Functions to Text Templates

You can create helper functions in text templates by enclosing them in class feature blocks. In text templates, you denote class feature tags by using <#+ #>. For more information, see Class Feature Syntax.

In this procedure, you create a text template and then add a basic helper function to it. The helper function returns a string that has the spaces removed.

To create a text template

  1. Create a new Visual Basic or C# class library named TemplateTest.

  2. Add a text file named Test.txt.

  3. Make sure that the Custom Tool property is set to TextTemplatingFileGenerator.

To add a helper function to a text template

  1. Add the following code to Test.txt.

    These initial directives set the output extension, import a namespace that the function will use, and identify the language (if necessary).

    <#@ output extension=".txt" #>
    <#@ import namespace = "System.Text.RegularExpressions" #>
    <#@ output extension=".txt" #>
    <#@ import namespace = "System.Text.RegularExpressions" #>
    <#@ template language="vb" #>
  2. Add the following code to Test.txt after the directives.

    This code is the helper function, and it is wrapped in class feature tags.

    private string FixWhiteSpaces(string s)
        return(Regex.Replace(s," ","").ToString());
    Private Function FixWhiteSpaces(ByVal s As String) As String
        return Regex.Replace(s, " ", "").ToString()
    End Function
  3. On the File menu, click Save Test.txt.

To use a helper function in a text template

  1. Add the following code to Test.txt.

    The code should go after the directives and before the class features. This code uses the helper function.

        WriteLine(FixWhiteSpaces(@"New York"));
        WriteLine(FixWhiteSpaces(@"San Francisco"));
        WriteLine(FixWhiteSpaces(@"New Delhi"));
        WriteLine(FixWhiteSpaces("New York"))
        WriteLine(FixWhiteSpaces("San Francisco"))
        WriteLine(FixWhiteSpaces("New Delhi"))
  2. On the File menu, click Save Test.txt.

  3. In Solution Explorer, right-click Test.txt, and then click Run Custom Tool.

  4. In Solution Explorer, expand Test.txt, and then double-click Test1.txt to open it in the editor.

    The generated text output appears and should resemble the following. Notice that spaces have been removed from the names.


See Also

Other Resources

Adding Code to Text Templates

Using Built-in Directives in Text Templates

Generating Artifacts By Using Text Templates

Change History




July 2008

Rewrote and refactored project.

Content bug fix.