【问题标题】:Running T4 templates from other T4 template从其他 T4 模板运行 T4 模板
【发布时间】:2011-04-07 20:34:47
【问题描述】:

有谁知道是否可以在 VS2010 中从另一个 T4 模板运行 T4 模板文件

谢谢

【问题讨论】:

    标签: visual-studio-2010 templates t4


    【解决方案1】:

    是的,你可以。我就是这样做的:

    string templateText = File.ReadAllText(Host.ResolvePath(templateFileName));
    Engine engine = new Engine();
    string output = engine.ProcessTemplate(templateText, Host);
    //this is optional - record all output to your file of choice:
    File.WriteAllText(outputFilePath, output); 
    

    【讨论】:

    • 这是否依赖于 T4 Toolbox?
    • 供将来参考:添加对 Microsoft.VisualStudio.TextTemplating.Interfaces.11.0 的引用并添加 和 到 T4 文件。
    【解决方案2】:

    您可能正在寻找的是T4 Toolbox。它将允许您在单个文件中实际生成代码并自动将它们添加到项目中。

    强烈推荐。

    我使用 t4 工具箱仅基于模型生成整个项目。

    (T4 Toolbox 以前位于 http://t4toolbox.codeplex.com/,但现在位于 https://github.com/olegsych/T4Toolbox

    【讨论】:

      【解决方案3】:

      我们经常这样做。下面是一个示例,我们如何重用一个通用 T4 模板但“传递参数”到其中:

      <#
      var currentUsername = "billclinton"; // this is for integration tests impersonating a user in our case
      #>
      <#@ include file="..\SomeTemplateThatIWantToReuseHere.tt" #>
      

      并且我们通过动态确定 T4 模板实际运行的位置(在本例中是包含 include 行的 T4 模板)来保持我们的 T4 模板“通用”:

      string namespaceName = code.VsNamespaceSuggestion();
      var namespaceParts = namespaceName.Split('.');
      var currentNamespaceLeg = namespaceParts.Last();
      

      这让我们可以做一些非常强大的模板而不需要复制我们的模板。唯一被“重复”的是我们的 4 行 .tt 文件,其中包含 include 调用,但除了我们想要通过以我们的方式传递变量来执行的任何“配置”之外,这些几乎是免维护的去做吧。

      【讨论】:

        【解决方案4】:

        有多个选项具有不同的权衡:

        http://www.olegsych.com/2008/04/t4-template-design/

        【讨论】:

        • 链接已损坏。答案中的描述会更好,
        猜你喜欢
        • 2011-04-26
        • 1970-01-01
        • 2011-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多