sebastienros / fluid

Fluid is an open-source .NET template engine based on the Liquid template language.
MIT License
1.44k stars 178 forks source link

Template not rendering #596

Closed kevit-yuvraj-kanakiya closed 2 months ago

kevit-yuvraj-kanakiya commented 1 year ago

Can someone check this whats wrong with this code. this is working fine in liquid js playground but when I converted it into c# code it is not working correctly.

using Fluid;
using System;
using System.Collections.Generic;

public class MyTemplateContext
{
    public object ApiResponseData { get; set; }
    public Dictionary<string, object> CustomFields { get; set; }
}

public class Program
{
    public static void Main()
    {
        var template = "FYI:- Your are applying OD from {{CustomFields.fromDate | date: '%d/%m/%Y'}} to {{CustomFields.toDate | date: '%d/%m/%Y'}} day(s).{% assign weekOffDates = ApiResponseData | where: \"isWeekOFfStatus\", true | map: \"shiftDate\" %}{% assign holidayDates = ApiResponseData | where: \"isHolidayStatus\", true | map: \"shiftDate\" %}{% if weekOffDates.size > 0 or holidayDates.size > 0 %}{% if weekOffDates.size > 0 %}{{ weekOffDates | join: \", \" }} are week offs.  {% endif %}{% if holidayDates.size > 0 %}{{ holidayDates | join: \", \" }} are holidays.{% endif %}{% endif %}";

        var context = new MyTemplateContext
        {
            ApiResponseData = new List<object>
            {
                new { shiftDate = "2023-10-01", isWeekOFfStatus = true, isHolidayStatus = false },
                new { shiftDate = "2023-10-02", isWeekOFfStatus = false, isHolidayStatus = true }
            },
            CustomFields = new Dictionary<string, object>
            {
                { "fromDate", "2023-10-01" },
                { "toDate", "2023-10-03" }
            }
        };

        var parser = new FluidParser();
        var result = parser.TryParse(template, out var parsedTemplate, out var errors);

        if (result)
        {
            var output = parsedTemplate.Render(new TemplateContext(context));

            Console.WriteLine(output);
        }
        else
        {
            Console.WriteLine("Template parsing failed with errors:");
            foreach (var error in errors)
            {
                Console.WriteLine(error);
            }
        }
    }
}

Output: FYI:- Your are applying OD from 01/10/2023 to 03/10/2023 day(s).

Expected Output (working in liquid js playground): FYI:- Your are applying OD from 01/10/2023 to 03/10/2023 day(s). 2023-10-01 are week offs. 2023-10-02 are holidays.

Fluid.Core : 2.5.0 .Net version: 6

sebastienros commented 2 months ago

new { shiftDate = "2023-10-01", isWeekOFfStatus = true, isHolidayStatus = false } is an anonymous object that is not "registered" in the allowed types. You need to register this type, please check the README for an example.