StubbleOrg / Stubble

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

Templating with ValueTuples. #107

Closed dmitry-lp closed 3 years ago

dmitry-lp commented 3 years ago

Is there a possibility to make Stubble work with Tuples (not the Tuple<> class but https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples)?

For exemple if I run

        var stubble = new StubbleBuilder().Build();

        string template ="<program name=\"{{Name}}\"></program>";

        Data data = new Data(){Name = "FooBar"};
        Console.WriteLine(stubble.RenderAsync(template, data).Result);

        var data2 = (Name: "FooBar", date:"01/01/2001");
        Console.WriteLine(stubble.RenderAsync(template, data2).Result);

The first print will inject FooBar but not the second one. This would be very usefull as often the data should be combined for template injection and it can be usefull to use tuples instead of declaring specific classes.

Romanx commented 3 years ago

Interesting, this should be possible to add but i'm aware that these names are actually syntactic sugar over Item1, ItemX with attributes identifying them across assembly.

I'll put this as a feature and see what we can do, thanks for your contribution!

dmitry-lp commented 3 years ago

Yes it looks like in some cases like Method results the compiler attaches TupleElementNamesAttribute but the objects are basically ValueTuples and as you said those are Item1, Item2, ... They have similar discussion on Newtonsoft.Json repo https://github.com/JamesNK/Newtonsoft.Json/issues/1230

dmitry-lp commented 3 years ago

Just tested and the workaround would be to use anonymous types. It works nice for me

        var data3 = new { Name = "FooBar", date = "01/01/2001" };
        Console.WriteLine(stubble.RenderAsync(template, data3).Result);
Romanx commented 3 years ago

Hi there,

Sorry for the delay at taking a look at this, I found that this was particularly difficult in that the atrribute containing the names of the tuple members is only added when the tuple is used as the return type of a method which isn't a guarantee when being passed to Stubble since it could be passed as a first class argument which may or may not have been given that information.

I'm going to consider this a won't fix and recommend that anyone wanting this functionalty use anonymous types since they're converted into object types with the given members at compile time.

Thanks for submitting the request and sorry that we couldn't support this

dmitry-lp commented 3 years ago

No that's ok. In this type of scenario named tuples and anonymous types are equivalent. Just I started by testing Tuples ;)