我正在尝试使用来自 http:/dotliquidmarkup.orgtry-online。.我有以下代码,使用NuGet包DotLiquid。
namespace 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 >
你可能错过了 new { tempuser = user }
你把匿名对象属性改名为 tempuser
在某些时候。这 new { user }
相当于 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 })));