我试图使用一个Handlebars.Net模板来迭代字符串列表,并根据字符串的值呈现一个或另一个。
这是一个削减的例子,我正在努力实现。我有一个具有string属性列表的对象,以及一个循环遍历该列表并根据字符串的值呈现一些HTML的模板:
带有list的简单对象:
public class Box
{
public List<string> BoxItems { get; set; }
}迭代列表并呈现一件或另一件事情的简单模板:
{{#each Box.BoxItems }}
{{#if this == "item" }}
<p>This is a box item</p>
{{else}}
<p>This is not a box item</p>
{{/if}}
{{/each}}我试过注册自己的助手,但没有成功。
如何使用Handlebars.Net端口(而不是HandlebarsJS版本)使其工作?
编辑:
我尝试使用的不起作用的助手是这样的:
handlebars.RegisterHelper("eq_test", (a, b) => a.ToString().Equals(b.ToString()));它用于模板中,如下所示:
{{#each Box.BoxItems }}
{{#if (eq_test this "item") }}
<p>This is a box item</p>
{{else}}
<p>This is not a box item</p>
{{/if}}
{{/each}}发布于 2022-09-07 11:54:18
回答我自己的问题,
我是这样注册帮手的:
handlebars.RegisterHelper("isEq", (ctx, args) => {
if (args.Length != 2)
{
throw new ArgumentOutOfRangeException();
}
string str1 = args[0].ToString();
string str2 = args[1].ToString();
return str1 == str2;
});然后我在模板中用了这样的方法:
{{#each Box.BoxItems }}
{{#if (isEq this item) }}
<p>This is a box item</p>
{{else}}
<p>This is not a box item</p>
{{/if}}
{{/each}}显然,这不是一个如何做到这一点的完美例子。没有对参数进行真正的检查,这显然是一个字符串比较。
但是希望它能为一些人节省几个小时的时间,找出如何为Handlebars.Net注册一个简单的等式检查助手。
https://stackoverflow.com/questions/73633658
复制相似问题