Handlebars-Net / Handlebars.Net.Helpers

Handlebars.Net helpers in the categories: 'Boolean', 'Constants', 'Enumerable', 'Environment', 'Math', 'Regex', 'String', 'DateTime' and 'Url'.
MIT License
40 stars 15 forks source link

Add String.Coalesce #60

Closed kspearrin closed 1 year ago

kspearrin commented 1 year ago

It would be nice to have a helper that coalesces to find the first non-null/empty/whitespace value. I created this helper to serve my needs (see below). I would submit a PR for this, but I am unsure how to add infinite argument helpers, given your existing helper examples are all finite.

Is there interest in such a helper for this library?

context.RegisterHelper("String.Coalesce", (context, arguments) =>
{
    foreach (var arg in arguments)
    {
        if (arg != null)
        {
            if (arg is string s)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    return arg;
                }
            }
            else
            {
                return arg;
            }
        }
    }
    return null;
});
Result: {{String.Coalesce "", " ", "", "a", "b", "", "c"}}
Result: a
StefH commented 1 year ago

Technically this should be possible. I'll take a look.

StefH commented 1 year ago

https://github.com/Handlebars-Net/Handlebars.Net.Helpers/pull/61

StefH commented 1 year ago

@kspearrin You can try preview 2.3.8-ci-16687

StefH commented 1 year ago

@kspearrin if this fix is ok, then i can create a new nuget which includes your pr + this one

kspearrin commented 1 year ago

@StefH Tested and looks good. Thanks.