Try to use DotLiquid with c#

我的梦境 提交于 2020-01-14 03:31:06

问题


I was unable to excute example in : http://dotliquidmarkup.org/try-online with C#. I have the same example and try to execute it with following code :

var template = DotLiquid.Template.Parse(myTemplate);
Message.Body = template.Render(DotLiquid.Hash.FromAnonymousObject(user));

Where myTemplate is exactly the same as in example :

<p>{{ user.name | upcase }} has to do:</p>
<ul>
{% for item in user.tasks -%}
  <li>{{ item.name }}</li>
{% endfor -%}
</ul>

But when hit Render i receive error : An exception of type 'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll but was not handled in user code and the inner message is : Parameter count mismatch.

My data type as i told is the same like in example :

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

public class Task
{
    public string Name { get; set; }
}

And i create object like that :

var user = new User
{
    Name = "Tim Jones",
    Tasks = new List<Task>
    {
        new Task { Name = "Documentation" },
        new Task { Name = "Code comments" }
    }
};

I can`t figure it out what is the issue with my code. Will appreciate any help ..


回答1:


You are using Hash.FromAnonymousObject which expects an anonymous object (as its name implies).

So pass an anonymous object:

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

Or, in your case (I haven't tested, but this should work):

template.Render(DotLiquid.Hash.FromAnonymousObject(new { user = this.user }));


来源:https://stackoverflow.com/questions/35431230/try-to-use-dotliquid-with-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!