jehugaleahsa / mustache-sharp

An extension of the mustache text template engine for .NET.
The Unlicense
306 stars 78 forks source link

Getting the root object in a custom tag definition #35

Closed bfcamara closed 9 years ago

bfcamara commented 9 years ago

Is it possible to get the root object in a custom tag definition?

Here what I'm trying to accomplish

    public class JsonPathTagDefinition : InlineTagDefinition
    {
        public JsonPathTagDefinition() : base("json")
        {
        }

        protected override IEnumerable<TagParameter> GetParameters()
        {
            return new TagParameter[] { new TagParameter("path") { IsRequired = true }}
        }

        public override void GetText(System.IO.TextWriter writer, Dictionary<string, object> arguments, Scope context)
        {
            string path = (string)arguments["path"];
            object source = null;
            bool found = context.TryFind("this", out source);

            var json = JObject.FromObject(source)
            String val = json.SelectToken(path).Value<String>();
            writer.Write(val);
        }
    }

Then I want to do this in my template

{{#jsonpath '$..book[2]'}}

Alternatively, I can define another parameter with the source object

{{#jsonpath this '$..book[2]'}}

But I'm trying to avoid it.

Any idea

jehugaleahsa commented 9 years ago

There is no easy way to ask a ScopeContext for it's parent. I can see it being useful to add a Parent property to the ScopeContext. You'd know you were at the top when the Parent is null. Then "this" would refer to the top of the stack.