在ST4 / C#中,你可以注册一个没有TemplateGroup的新渲染器吗?

时间:2014-08-13 16:33:31

标签: c# stringtemplate stringtemplate-4

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

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

2 个答案:

答案 0 :(得分:1)

好吧,我想出了如何从字符串中创建模板组(这里的文档并不好,特别是对于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();

答案 1 :(得分:0)

RegisterRenderer()方法可通过Group - 属性:

获得
Dim tmpl As New Template(s, "$", "$")
tmpl.Group.RegisterRenderer(GetType(DateTime), New MyDateRenderer())