从其他T4模板运行T4模板。

问题描述 投票:9回答:4

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

谢谢

visual-studio-2010 templates t4
4个回答
7
投票

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

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); 

3
投票

你可能要找的是 T4工具箱. 它将允许你实际生成单个文件中的代码,并将它们自动添加到一个项目中。

强烈推荐。

我曾用t4工具箱生成整个项目,只是基于一个模型。

(T4工具箱以前的位置是在 http:/t4toolbox.codeplex.com 但现在是在 https:/github.comolegsychT4Toolbox。 )


1
投票

有多种选择,有不同的取舍。

http:/www.olegsych.com200804t4-template-design


1
投票

我们经常这样做。下面是一个例子,我们如何重用一个普通的T4模板,但又将参数 "传入 "它。

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

我们通过动态确定T4模板实际运行的位置来保持T4模板的 "通用性"(在本例中,T4模板有以下功能 include 行)。)

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

这样我们就可以做一些非常强大的模板,而不需要重复我们的模板。唯一被 "复制 "的是我们的4行的 .tt 的文件。include 调用它们,但除了我们想通过传递变量的方式来执行任何 "配置 "外,这些都是几乎不需要维护的。

© www.soinside.com 2019 - 2024. All rights reserved.