Dotliquid Date Filter

2.4k views Asked by At

I am trying to calculate the days between "now" and a provided date. I found a SO post that seems to do exactly what I am looking for. Shopify (liquid): Find number of days between two dates

Unfortunately, when i change it for my model I experience problems. After some debugging my guess is it is related to dates with an applied filter, in my situation "minus".

If I do something like:

{{"now" | date: "%s" }}

I get a valid result. But once i apply a filter to it:

{{"now" | date: "%s" | minus: 604800 }}

I get "Liquid error: Parameter count mismatch."

I also made sure that it isn't the minus filter, i tried basic math like:

{{ 100 | minus : 20 }}

and it was successful to print "80".

Is there a setting i am forgetting? I have these settings turned on.

Liquid.UseRubyDateFormat = true;
Template.NamingConvention = new DotLiquid.NamingConventions.RubyNamingConvention();

Thanks!

1

There are 1 answers

0
T.S. On

With this, {{"now" | date: "%s" }} you were not far from "truth". This is how it works

private static void SmallTest()
{
    const string templateString = @"xxx '{{ k1 | Date : ""D""  }}' yyy";
    Template.NamingConvention = new CSharpNamingConvention();
    var t = Template.Parse(templateString);
    string output = t.Render(Hash.FromDictionary(new Dictionary<string, object>(){ { "k1", "now" } }));
    Console.WriteLine("NOW --> " + output);
}

What I found out, filter Date is case sensitive. It doesn't get picked up with date.

But I don't think you can do minus on the date. What you need is custom filter

public static class TextFilters
{
    public static string DaysFromNow(object input)
    {
        return DateTime.Now.AddDays(Convert.ToDouble(input)).ToString();
    }
}

Template.RegisterFilter(typeof(TextFilters));

Usage: {{ k2 | DaysFromNow }} Rendering:

Hash.FromDictionary(new Dictionary<string, object>(){ { "k2", -10 } }));

All code above is tested and working