WeihanLi / WeihanLi.Common

common tools, methods, extension methods, etc... .net 常用工具类,公共方法,常用扩展方法等,基础类库

Home Page:https://weihanli.github.io/WeihanLi.Common/index.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

templating enhancements

WeihanLi opened this issue · comments

  • support get value from the environment

For example:

var result = TemplateEngine.CreateDefault().RenderAsync("Hello {{$env USERNAME}}");
Console.WriteLine(result);

API changes:

public interface ITemplateRenderer
{
-     Task<string> RenderAsync(TemplateRenderContext template, object globals);
+     Task<string> RenderAsync(TemplateRenderContext template, object? globals = null);
}
  • support configuration

Maybe we could add a IConfiguration in TemplateOptions, allow reading from config

usage example:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    // .AddXxx()
    .Build();
var result = TemplateEngine.Create(options => 
{
    options.Configuration = configuration;
}).RenderAsync("Hello {{$config USERNAME}}");
Console.WriteLine(result);
  • DependencyInjection extension

and we could add the dependency injection extension to bind to the default app configuration if there's a configuration

var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection([new("UserName", "test")]).Build());
services.AddTemplating();
await using var provider = service.BuildServiceProvider();

var templateEngine = provider.GetRequiredeService<ITemplateEngine>();
var result = await templateEngine.RenderAsync("Hello {{$config UserName}}");
Console.WriteLine(result);
// Hello test