如何覆盖Handlebars的`if`帮助器

问题描述 投票:0回答:1

我正在寻找一种方法来改变Handlebars的if助手的工作原理。

Mandrill已将a few modifications制作成标准车把。其中一个方便的变化是它们处理Handlebars的if块助手的方式。他们添加了在if助手中评估表达式的能力,如下所示: {{#if `purchases > 3`}}

我需要能够在本地编译Mandrill模板,用于测试和预览,而这个功能使得它变得困难。我知道我可以编写自己的自定义助手,但在这种情况下,我正在寻找一种方法来改变内置的if助手的工作方式。

我想我可以建立自己的Handlebars版本。 还有其他建议吗?

handlebars.js mandrill
1个回答
0
投票

只要你的工作正常,我认为重新定义标准助手是没有问题的。您将在下面的代码段中找到一个覆盖if帮助器而不是文本的示例。所以只需注册你自己的助手,这将覆盖默认的助手。如果你想让{{else}}也工作,你必须在你的if帮助代码中处理它。

 
$(document).ready(function () {
  var context = {
    "textexample1" : "hello",
  };
  Handlebars.registerHelper('if', function(text) {
    return new Handlebars.SafeString(text);
  });
	var source   = $("#sourceTemplate").html();
  var template = Handlebars.compile(source);
  var html    = template(context);
  $("#resultPlaceholder").html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="sourceTemplate" type="text/x-handlebars-template">
{{#if 'test override'}}
   {{textexample1}}
{{/if}}
</script>
<br/>
<div id="resultPlaceholder">
</div>
© www.soinside.com 2019 - 2024. All rights reserved.