【问题标题】:Handlebars.Net How to change behavior if data does not existHandlebars.Net 如果数据不存在如何改变行为
【发布时间】:2021-01-30 09:08:46
【问题描述】:

在 Handlebars.Net 中,如果没有匹配的字段,它只是在那里放置一个空白。

string source = @"My name is {{Name}} and I work at {{Job}}";
var template = Handlebars.Compile(source);
var data = new {
    Job = "Walmart"
};
var result = template(data);

导致这个是因为{{Name}} 不在数据中。

我的名字是,我在沃尔玛工作

有没有设置说,数据字段不存在就不要替换?

我希望它返回:

我叫 {{Name}},在沃尔玛工作

【问题讨论】:

    标签: handlebars.js handlebars.net


    【解决方案1】:

    有两种选择:

    1. 在 1.x 中支持:使用 UnresolvedBindingFormatter

      handlebars.Configuration.UnresolvedBindingFormatter = "('{0}' is undefined)";

    2. 2.0.0-preview-1开始支持:使用helperMissing hook

      handlebars.RegisterHelper("helperMissing", (context, arguments) =>
      {
          var name = arguments.Last().ToString();
          return "{{" + name.Trim('[', ']') + "}}";
      });
      

    更多详情请见this GitHub issue

    【讨论】:

      【解决方案2】:

      我认为您必须使用#if,例如:

      My name is {{#if Name}}{{Name}}{{else}}\{{Name}}{{/if}} and I work at {{Job}}

      注意:感谢answer 告诉我如何告诉 Handlebars 渲染大括号。

      【讨论】:

        猜你喜欢
        • 2010-10-12
        • 2017-04-24
        • 2017-04-11
        • 2019-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-10
        相关资源
        最近更新 更多