c# - 在 ST4/C# 中,是否可以在没有 TemplateGroup 的情况下注册一个新的渲染器?

标签 c# stringtemplate stringtemplate-4

RegisterRenderer 方法唯一出现的地方是在 TemplateGroup 上。但我只有一个模板,通过字符串提供,而不是文件系统上的多个模板。

或者,我如何使用 TemplateGroup 但通过字符串提供模板?

最佳答案

好吧,我想出了如何从字符串中创建模板组(这里的文档不是很好,尤其是对于 C# 端口)。虽然不是实际问题的解决方案,但它是一种解决方法,因为我可以向该组注册自定义渲染器。

本质上,我正在为单个模板创建一个模板组,这看起来很愚蠢,但无论如何:

// Create the group (I'm specifying custom delimiters, but you don't have to)
var group = new TemplateGroup('$','$');

// Here's where we bind the renderers to a type. They will run on EVERY occurrence of this type, which means you have to handle situations in your renderer where no format string was specified -- that's still gonna get run through the renderer (very important with strings, for instance)
group.RegisterRenderer(typeof(DateTime), new DateRenderer());

//Here's where you "register" (define) a template. You have to give it a name, and (weirdly) specify all the attributes you're going to use
group.DefineTemplate("default", "[template code here]", new string[] { "nameOfAttribute" });
// You can define more templates here...

// Now, get the template back out using the name you used before
var template = group.GetInstanceOf("default");

// Add the data (correctly using the names specified when you defined the template above)
template.Add("nameOfAttribute", my attribute);

// Render
var result = template.Render();

关于c# - 在 ST4/C# 中,是否可以在没有 TemplateGroup 的情况下注册一个新的渲染器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25291535/

相关文章:

java - StringTemplate 缩进在 String 中添加空格

java - 如何使用 Stringtemplate 4.x 直接写入 OutputStream?

java - 从文件 StringTemplate 中读取模板

c# - WPF 富文本框的冲突语言设置

c# - 如何在单元测试 ASP.NET Core Controller 时正确模拟 IAuthenticationHandler

java - Stringtemplate:是否可以将HashMap使用的模板应用于多值属性

java - 如何让 StringTemplate V4 忽略 < 作为分隔符?

c# - 检索物理核心处理器的数量

c# - 有约束的结构