从其他T4模板运行T4模板

时间:2010-09-03 13:17:24

标签: visual-studio-2010 templates t4

有没有人知道是否可以从VS2010内的另一个T4模板运行T4模板文件

感谢

4 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

您可能正在寻找的是http://t4toolbox.codeplex.com/ t4工具箱。它允许您在单个文件中实际生成代码并自动将它们添加到项目中。

强烈推荐。

我使用t4工具箱只根据模型生成整个项目。

答案 2 :(得分:1)

有多种选择可以有不同的权衡:

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

答案 3 :(得分:1)

我们做了很多。下面是一个示例,我们如何重用一个常见的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调用,但除了我们想通过传入变量执行的任何“配置”之外,它们几乎都是免维护的我们这样做的方式。