0

我正在尝试使用http://dotliquidmarkup.org/try-online中的示例。我使用 NuGet 包 DotLiquid 有以下代码

命名空间 TestDotLiquidLoop {

public class User : Drop
{
    public string Name { get; set; }
    public List<Task> Tasks { get; set; }
}

public class Task
{
    public string Name { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        //Console.WriteLine("Hello World!");

        //const string template1 = "{{ user.name | upcase }} has to do:{% for item in user.tasks -%}{ { item.name } }{% endfor -%}";
        const string template = "<p>{{ user.name | upcase }} has to do:</p>" +
            "< ul >{% for item in user.tasks -%}" +
            "< li >{ { item.name } }</ li >" +
            "{% endfor -%}" +
            "</ ul > ";
        Template preparedTemplate = Template.Parse(template);


        var user = new User
        {
            Name = "Tim Jones",
            Tasks = new List<Task>
        {
            new Task { Name = "Documentation" },
            new Task { Name = "Code comments" }
        }
        };
        Console.WriteLine(preparedTemplate.Render(DotLiquid.Hash.FromAnonymousObject(new { tempuser = user })));

    }
}

}

我没有正确获得输出。我的输出是这样的。我知道这很愚蠢,但有人可以帮我解决这个问题吗?

<p> has to do:</p>< ul ></ ul >
4

1 回答 1

0

您可能错过了在某个时候new { tempuser = user }将匿名对象属性重命名为。tempusernew { user }相当于this new { user = user }。要引用tempuser内部模板,您只需更改名称。

        string template = "<p>{{ tempuser.name | upcase }} has to do:</p>" +
                                "< ul >{% for item in tempuser.tasks -%}" +
                                "< li >{{ item.name }}</ li >" +
                                "{% endfor -%}" +
                                "</ ul > ";
        Template preparedTemplate = Template.Parse(template);

        var user = new User
        {
            Name = "Tim Jones",
            Tasks = new List<Task>
            {
                new Task { Name = "Documentation" },
                new Task { Name = "Code comments" }
            }
        };
        Template.RegisterSafeType(typeof(Task), new []{"Name"});
        Console.WriteLine(preparedTemplate.Render(DotLiquid.Hash.FromAnonymousObject(new { tempuser = user })));
于 2020-06-10T12:09:36.573 回答