如何在Handlebars.Net模板中实现字符串比较?
在Handlebars.Net中遍历字符串列表并根据值渲染不同内容
问题根源
Handlebars(包括.Net版本)的{{if}}助手不支持直接在条件中使用==进行值比较,必须借助自定义助手实现;你之前注册自定义助手的签名不符合Handlebars.Net的要求,导致助手失效。
可行解决方案
方案1:注册返回布尔值的比较助手(用于{{if}}条件)
注册一个能返回布尔值的自定义助手,作为{{if}}的判断条件:
using HandlebarsDotNet; var handlebars = Handlebars.Create(); // 注册自定义相等判断助手 handlebars.RegisterHelper("eq", (context, arguments) => { // 校验参数数量 if (arguments.Length != 2) return false; // 处理空值,转为字符串后比较 var val1 = arguments[0]?.ToString(); var val2 = arguments[1]?.ToString(); // 按精确匹配比较,可根据需求改为StringComparison.OrdinalIgnoreCase忽略大小写 return string.Equals(val1, val2, StringComparison.Ordinal); });
对应的模板写法:
{{#each Box.BoxItems }} {{#if (eq this "item") }} <p>This is a box item</p> {{else}} <p>This is not a box item</p> {{/if}} {{/each}}
方案2:注册块级助手(直接替代if-else逻辑)
如果不想嵌套{{if}},可以直接注册一个块级助手,内置判断逻辑:
handlebars.RegisterHelper("when_eq", (options, context, arguments) => { if (arguments.Length != 2) { options.Inverse(context); return; } var val1 = arguments[0]?.ToString(); var val2 = arguments[1]?.ToString(); if (string.Equals(val1, val2, StringComparison.Ordinal)) { // 值匹配时渲染主内容块 options.Template(context); } else { // 值不匹配时渲染else内容块 options.Inverse(context); } });
对应的模板写法:
{{#each Box.BoxItems }} {{#when_eq this "item"}} <p>This is a box item</p> {{else}} <p>This is not a box item</p> {{/when_eq}} {{/each}}
测试示例
创建测试数据并渲染模板:
// 你的Box类定义 public class Box { public List<string> BoxItems { get; set; } } // 构造测试数据 var testBox = new Box { BoxItems = new List<string> { "item", "book", "item", "pen" } }; // 编译并渲染模板 var template = handlebars.Compile(yourTemplateContent); var renderedHtml = template(testBox);
内容的提问来源于stack exchange,提问作者Serigan
相关产品推荐
相关产品推荐

