sebastienros / fluid

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

I can't see the iterated value in the result #649

Closed MesutKeklik closed 1 month ago

MesutKeklik commented 1 month ago

Here is my sample code:

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

public class StrObj
{
    public string Str {get;set;}
}

public class TestObj
{
    public List<StrObj> StrObjects {get;set;}
}

public static class Program
{   
    public static void Main()
    {
        var templateText = "{% for item in StrObjects %} String: {{ item.Str }} {% endfor %}";

        var testObj = new TestObj();
        testObj.StrObjects = new List<StrObj>();
        testObj.StrObjects.Add(new StrObj { Str = "test1" });
        testObj.StrObjects.Add(new StrObj { Str = "test2" });
        testObj.StrObjects.Add(new StrObj { Str = "test3" });
        testObj.StrObjects.Add(new StrObj { Str = "test4" });

        var parser = new FluidParser();
        if (parser.TryParse(templateText, out IFluidTemplate template, out string error))
        {
            var ctx = new Fluid.TemplateContext(testObj);
            var html = template.Render(ctx);

            Console.WriteLine(html);
        }
        else
        {
            Console.WriteLine($"Error in html template parser! {error}");
        }
    }
}

the expected result is String: test1 String: test2 String: test3 String: test4

but it returns String: String: String: String:

Based on the result I can tell the for loop works, but why I can't see the values?

MesutKeklik commented 1 month ago

I found the problem. If we need to use a nested object, we need to register it before calling the render function.