StubbleOrg / Stubble

Trimmed down {{mustache}} templates in .NET
Other
401 stars 58 forks source link

set default value if token not found #73

Closed ashtonian closed 4 years ago

ashtonian commented 4 years ago

I'm trying to figure out how to intercept the token resolver so that I can provide a different value if the key is not in the context dictionary. My specific use case is that I will always have an entity ID but may not have details on that entity and would like to print the id instead of the details when details are not present.

Hello {{User.Email}},  //  want to default to value to "user: {{User.Id}}" as this will always be populated. 

I've tried playing with the value getter but couldn't get it to do what I wanted - is there any other hook I should look at ?

        private StubbleVisitorRenderer _builder = new StubbleBuilder()
              .Configure(settings =>
              {
                  settings.AddValueGetter(typeof(IDictionary<string, object>), (key, value, ignoreCase) =>
                  {

                      Console.WriteLine("HERE", key, value, ignoreCase); // won't trigger 
                      return value;
                  });
Romanx commented 4 years ago

Hi there,

I currently have spotty access to internet so won't be able to look for a few days but i'll assign this to myself to give you feedback when I can.

builder-main commented 4 years ago

I'd advise to either

Romanx commented 4 years ago

@Ashtonian Sorry for taking some time to get back to you. I've tested the example you gave and was able to hit a breakpoint in the value getter. The value getter only gets called if it's the same type or assignable to the given type so the argument has to be a Dictionary<string, object> for this to be called. The catch all handler is object and so the bottom type.

However I would agree with @MorphiksBuilder and pre-processing your input values and simplifying your template is recommended here otherwise you get into the realm of your template being bound to how the renderer works and being brittle.

I'm going to close this now but please feel free to open another issue if there's a feature you think may help you.

Thanks,