antlr / antlrcs

The C# port of ANTLR 3, StringTemplate 3, and StringTemplate 4

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add support for C# dynamics

tubededentifrice opened this issue · comments

TemplateGroup tg=new TemplateGroupString("test",@"
test(a,b,c) ::= <<
a = $a$
a.name = $a.name$
b = $b$
b.name = $b.name$
c = $c$
c.name = $c.name$
>>
",'$','$');

Template t=tg.GetInstanceOf("test");

object a=new { name = "A object" };
t.Add("a",a);

object b= Newtonsoft.Json.JsonConvert.DeserializeObject("{ name: \"B object\" }");
t.Add("b",b);

dynamic c=new ExpandoObject();
c.name="C object";
t.Add("c",c);

System.Console.WriteLine(t.Render());

The output is:

a = { name = A object }
a.name = A object
b =
b.name =
c = [name, C object]
c.name =

Expected output:

a = { name = A object }
a.name = A object
b = (not really matters)
b.name = B object
c = [name, C object]
c.name = C object

I can't find any other way to be able to preview my templates easily (user passes a JSON object, deserialized into a Dictionary<string,dynamic>, then each dictionary KVP are sent to the template individually).
Let me know if you need clarification about this use case.

For the dynamic object c, you just need to implement IModelAdaptor and register it for the type IDynamicMetaObjectProvider by calling TemplateGroup.RegisterModelAdaptor. You can refer to ObjectModelAdaptor for an example of how to implement this interface.

You can do the same for a JObject (or JToken) to handle the case for b.

Thanks for your help Sam, it worked; but don't you think it should be natively supported? It seems to be a pretty common use case in .NET, isn't?
Also IModelAdaptor would probably benefits from being generic (it's probably the way it is because it's a Java port), but this is not related to this particular issue, off topic.