Fluid Parser 不显示迭代值

问题描述 投票:0回答:1

我有一个c#示例代码

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}");
        }
    }
}

这段代码应该返回类似这样的内容

String: test1 String: test2 String: test3 String: test4

但是,它会返回

String: String: String: String:

它写了 4 次“String:”,这意味着模板中的 for 循环可以工作,但为什么我看不到这些值?

我也将此示例添加到 dotnetfiddle 中。 https://dotnetfiddle.net/wIq9mS

提前致谢!

c# shopify liquid fluid
1个回答
0
投票

我发现了问题,不知何故 Fluid 看不到内部对象。所以我们需要在调用解析器之前注册它们。

解决方案如下:

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))
    {
        /* Following lines necessary if you have a nested object */
        var options = new TemplateOptions();
        options.MemberAccessStrategy.Register<StrObj>();
        
        var ctx = new Fluid.TemplateContext(testObj, options);
        var html = template.Render(ctx);

        Console.WriteLine(html);
    }
    else
    {
        Console.WriteLine($"Error in html template parser! {error}");
    }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.