.NET 8 C# 使用模板引擎 Scriban

文章目录

    由于 C# 中没有像 golang 一样内置一个模板引擎,所以做一下选型。

    选型一:T4 text templates

    https://learn.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2022

    没有看懂是否能够在 Visual Studio 之外使用,所以放弃。

    选型二:类 razor 模板引擎

    https://github.com/toddams/RazorLight

    比较喜欢 Razor 的语法,但是这个项目引入政治元素,而且看起来文档也有点乱。
    不太敢尝试。

    选型三:scriban (最终使用)

    https://github.com/scriban/scriban

    Scriban is a fast, powerful, safe and lightweight scripting language and engine for .NET, which was primarily developed for text templating with a compatibility mode for parsing liquid templates.

    相比选型二,这个文档更清晰,用的人也多。所以先试用一下。

    安装 scriban 依赖

    dotnet.exe add package Scriban --version 5.10.0
    

    scriban 基本示例

    // Parse a scriban template
    var template = Template.Parse("Hello {{name}}!");
    var result = template.Render(new { Name = "World" }); // => "Hello World!"
    

    变量无法替换

    奇葩的是,模板中的变量名需要用小写 hello_world 这样的形式,而不能是 helloWorld 的格式。
    否则,无法替换。

    scriban 不支持 AOT

    .nuget\packages\scriban\5.10.0\lib\net7.0\Scriban.dll : warning IL2104: Assembly 'Scriban' produced trim warnings.
    .nuget\packages\scriban\5.10.0\lib\net7.0\Scriban.dll : warning IL3053: Assembly 'Scriban' produced AOT analysis warnings.
    

    publish 的文件大小

    Scriban.dll 有 439K 大。

    > ls bin/Release/net8.0/publish/ -lah
    total 812K
    439K  Scriban.dll*
    201K  System.CommandLine.dll*
    12K    xxx.dll*
    140K  xxx.exe
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式