T4代码摘要生成(无自动编译,无自动文件管理)



在这种情况下,我们基本上想要通过传递模板内容的参数和模板自身构建所需的信息来生成代码文件的字符串表示:

//***  PSEUDO CODE *** //
//loaded from an embedded resource file in a .dll. no physical file on file system
string templateContents = ...; 
//has properties used by the template 
object complexParameter = ...; 
string generatedCode = generator.MakeCode(templateContents, complexParameter);

然而,我们目前在试图让T4模板生成实现我们想要的功能时遇到了问题。我们使用的实际代码是:

var templatingEngine = new Engine();
//T4TextTemplateHost is our own class implementing ITextTemplatingEngineHost & IServiceProvider
var templateHost = new T4TextTemplateHost(references, imports)
{
    Properties = parameters,
    //this is supposed to be a file path? the generation bombs if this is left null
    TemplateFile = "Dummy Value"
};
var templateContents = GetTemplateFileContents();
var retVal = templatingEngine.ProcessTemplate(templateContents, templateHost);
//if a CompilerError occurs, we get NO code, just a "ErrorGeneratingOutput" message
foreach (CompilerError error in templateHost.Errors)
    //this information is pretty worthless: a compile error with line number for a 
    //non-existant code file
    retVal += String.Format("{0}{2}Line: {1}{2}{2}", error.ErrorText, 
                            error.Line, Environment.NewLine);

问题是,代码生成器似乎希望在某个地方有一个物理文件,当出现问题时,我们不会得到代码,我们会得到无用的错误消息。我们强烈建议不要自动编译代码,尤其是当生成的代码出现错误时(我们希望在进行故障排除时检查一个完整、损坏的文件)。

我们还希望输出是一个字符串,我们可以随心所欲。

有没有一种方法可以让T4代码生成更像伪代码示例?我们即将放弃T4工具,转而使用CodeSmith这样的工具,因为T4似乎太有限了/太倾向于管理模板和处理输出的特定方式。

如果您传入的模板中存在错误,我认为不可能让T4生成任何内容。T4将尝试用额外的语句将您的模板转换为codedom,这些语句将写入字符串编写器,然后返回最终的字符串编写器作为结果。如果模板中有任何错误,代码将不兼容,因此它将不会返回给您。您返回的错误应该解决您传入的模板中的行,至少这是我的经验。

我不确定Code-Smith是否以不同的方式工作,但根据您试图呈现的内容的复杂性,如果它足够简单,您可能会幸运地使用Nustache。这是一个点网版的胡子模板。它支持基本的循环和if/then类型控制块。我已经成功地将它与嵌入的文本文件一起用于生成电子邮件和报告的简单模板。

最新更新