Running a T4 template using C#

后端 未结 2 553
野的像风
野的像风 2021-02-02 14:18

I have T4 template (mycode.tt) which generates a cs file. I usually right click the tt file and select RunCustomTool which internally takes an xml file and generate code for me.

相关标签:
2条回答
  • 2021-02-02 14:39

    You can easily achieve it, when you using VS2010. If you add a new file to the project, choose a preprocessed text template file. You can edit the template just as normal. Instead of generating the output directly, the file generates the code that is generated normally. I know it sounds confusing. But what you see in your output file is the code generated by the text templating toolkit to get your output (more or less).

    This is a short example of a preprocessed text template named "TestTemplate.tt" and how do you use it in your code:

    The tt-file:

    <#@ template language="C#" #>
    Some output.
    

    Code:

    using System;
    using System.Diagnostics;
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                TestTemplate testTemplate = new TestTemplate();
                Debug.Print(testTemplate.TransformText());
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-02 14:50

    I'd recommend the preprocessed route as answered above by @jb_.

    As an alternative, if you need your templates to still be editable without a compile step for use with your custom C# application, and the application will only be deployed on machines alongside Visual Studio, you can write a custom host.

    http://msdn.microsoft.com/en-us/library/bb126519.aspx

    0 讨论(0)
提交回复
热议问题