从 .Net Core 控制台应用程序调用 Mono.TextTemplating

Call Mono.TextTemplating from .Net Core console application

我已经将 NuGet Mono.TextTemplating 包安装到我的项目中,但我没有找到任何示例来从我的应用程序调用它。我创建了模板,并想从我的代码中使用参数调用生成器。

有什么建议吗?有没有 Mono.TextTemplating API 文档?

谢谢

刚刚查看 Mono.TextTemplating in the readme section it says that the T4 documentation can be found here 的 github 页。它有多个小节,并带有示例进行解释。希望对您有所帮助。

没找到官方文档,可以参考usage code.
而且,基本用法如下:

string inputFile = "TextTemplate1.tt"; // define your T4 template first
string outputFile = "outputfile";
var generator = new TemplateGenerator ();
generator.ProcessTemplate (inputFile, outputFile);

总结上面的所有答案和参考资料,我认为这里是如何开始的。

  1. 安装 Mono.TextTemplating NuGet 包。
  2. this page 中获取 T4 模板示例并将其保存为 C:\TEMP\Mono-Templates\MyTemplate1.tt(文件内容如下)。
  3. 从 lumen 借用代码 运行。您将获得 MyTemplate1Output.html 文件。
  4. 现在学习更多 T4 templates 并开始游戏。

P.S。 MS 为 .NET 5 引入了 C# Source Generators 作为一种新的生成方式。

代码片段:

string inputFile = @"C:\TEMP\Mono-Templates\MyTemplate1.tt";
string outputFile = @"C:\TEMP\Mono-Templates\MyTemplate1Output.html";
var generator = new Mono.TextTemplating.TemplateGenerator();
generator.ProcessTemplate(inputFile, outputFile);
if (generator.Errors.HasErrors)
{
    var consoleColor = Console.ForegroundColor;
    Console.ForegroundColor = ConsoleColor.Red;
    foreach (var error in generator.Errors)
        Console.WriteLine (error);
    Console.ForegroundColor = consoleColor;
}

文件 C:\TEMP\Mono-Templates\MyTemplate1.tt :

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<html><body>
<h1>Sales for Previous Month</h2>
<table>
    <# for (int i = 1; i <= 10; i++)
       { #>
         <tr><td>Test name <#= i #> </td>
             <td>Test value <#= i * i #> </td> </tr>
    <# } #>
 </table>
This report is Company Confidential.
</body></html>

结果文件 - MyTemplate1Output.html

<html><body>
<h1>Sales for Previous Month</h2>
<table>
             <tr><td>Test name 1 </td>
             <td>Test value 1 </td> </tr>
             <tr><td>Test name 2 </td>
             <td>Test value 4 </td> </tr>
             <tr><td>Test name 3 </td>
             <td>Test value 9 </td> </tr>
             <tr><td>Test name 4 </td>
             <td>Test value 16 </td> </tr>
             <tr><td>Test name 5 </td>
             <td>Test value 25 </td> </tr>
             <tr><td>Test name 6 </td>
             <td>Test value 36 </td> </tr>
             <tr><td>Test name 7 </td>
             <td>Test value 49 </td> </tr>
             <tr><td>Test name 8 </td>
             <td>Test value 64 </td> </tr>
             <tr><td>Test name 9 </td>
             <td>Test value 81 </td> </tr>
             <tr><td>Test name 10 </td>
             <td>Test value 100 </td> </tr>
     </table>
This report is Company Confidential.
</body></html>