views:

164

answers:

1

Hi

I am using string template to render some content, but the content may be variable so not sure how to pass it in (using .net / c#)

Basic idea is I have a List> which need to end up as parameters, e.g.

List<KeyValuePair<string, object>> ret = new List<KeyValuePair<string, object>>();
ret.Add(new KeyValuePair<string, object>("elem1", true));
ret.Add(new KeyValuePair(string, object>("elem2", false));

Now I want these to show up in string template as:

$item.elem1$ $item.elem2$

I can get them to be $elem1$ or $elem2$ but i need them inside of a structure. So I in effect need to convince the string template setAttribute that I'm passing in an object with properties elem1 and elem2 when in fact I have a List of KeyValuePairs.

Thanks

+2  A: 

Actually a very small re-write of that should work. You need to use a dictionary, and you can even nest them (using ST 3.2):

[Test]
public void When_Building_Text_With_A_Dictionary_As_The_Attributes_It_Should_Map_Members_To_Keys()
{
    IDictionary<string, object> ret = new Dictionary<string, object>();
    ret["elem1"] = true;
    ret["elem2"] = false;

    var nestedObj = new Dictionary<string, object>();
    nestedObj["nestedProp"] = 100;
    ret["elem3"] = nestedObj;

    var template = new StringTemplate("$elem1$ or $elem2$ and value: $elem3.nestedProp$");
    template.Attributes = ret;

    StringBuilder sb = new StringBuilder();
    StringWriter writer = new StringWriter(sb);
    template.Write(new NoIndentWriter(writer));
    writer.Flush();

    var renderedText = sb.ToString();

    Assert.That(renderedText, Is.EqualTo("True or False and value: 100"));
}

Myself and a colleague were looking to replicate the functionality of STST (ST Standalone Tool), which uses json as the properties, and we built a simple JObject to dictionary converter, I can post that code and an example if it's of any use to you, it's only ~20 lines.

Diego V
Thanks, in the end I ended up using CS-Script to run some code that I create dynamically containing the object... this worked for us because we were already running dynamic code in other places of the same project... but may go back to it and use your solution should we need more optimisation.
Mark Milford