如何在另一个自定义帮助程序中调用一个自定义辅助程序函数

How to call one custom helper function in another custom helper

本文关键字:自定义 一个 程序 函数 另一个 帮助程序 调用      更新时间:2023-09-26

我想在另一个助手函数中使用一个助手功能。在下面的代码中,如果姓氏包含"芬奇"这个词,我想突出显示它。我有写作助手类。如果我们在hbs文件中使用,那么语法将是{{highlight-name}}。但是如何使用它,因为我必须在另一个助手类中使用它。

以下是我的代码:

  Handlebars.registerHelper('fullName', function(person) {
    return person.firstName + " " + person.lastName;
  });
   Handlebars.registerHelper('highlight', function(person) {    
var item = (person.lastName).replace('Finch', '<span style="color: red">' 
  + Finch + '</span>');
return new Handlebars.SafeString(item); 
  });

这是工作小提琴:http://jsfiddle.net/wC6JT/4/

这是一把小提琴,"高光"辅助器被称为小提琴。:http://jsfiddle.net/wC6JT/3/。这不会产生任何结果,因为我们将得到person.lastName的控制台错误,在"高亮显示"注册助手中无法识别。

我想在person.lastName的全名助手中使用"高亮显示"助手。这是怎么实现的。

要从另一个函数调用Handlebars助手,可以使用Handlebars.helpers:

Handlebars.registerHelper('fullName', function(person) {
    var lastName = Handlebars.helpers.highlight.apply(this, [person.lastName]);
    var firstName = Handlebars.Utils.escapeExpression(person.firstName);
    return new Handlebars.SafeString(firstName + " " + lastName);
});
Handlebars.registerHelper('highlight', function(str) {    
    var safeStr = Handlebars.Utils.escapeExpression(str);
    var item = safeStr.replace("Finch", "<em>Finch</em>");
    return new Handlebars.SafeString(item); 
});

这是一把正在工作的小提琴:http://jsfiddle.net/acLcsL6h/1/

阅读这篇博客文章以获取另一个例子。

将要在第一个方法中使用的方法的内容提取到其自己的javascript方法中。然后根据需要在两个助手中调用该javascript方法。

除非将其中一个方法的内容重构为其自己的javascript方法,否则无法执行此操作。

所以在你的情况下,它应该看起来像这样:

Handlebars.registerHelper('fullName', function(person) {
    return person.firstName + " " + highlightJavascript(person);
  });
Handlebars.registerHelper('highlight', highlightJavascript);
highlightJavascript : function(person) {
   var item = (person.lastName).replace('Finch', '<span style="color: red">' 
  + Finch + '</span>');
return new Handlebars.SafeString(item); 
}

您可以使用这种方式:http://goo.gl/oY4IIO不需要连接字符串。

<script id="tmp" type="text/x-handlebars-template">
    <p>test:   {{test   "2.3333333"}}</p> 
    <p>format: {{format "2.3333333"}}</p>
</script>

Handlebars.registerHelper('format', function (value) {
   return parseFloat(value).toFixed(2);
});
Handlebars.registerHelper('test', function (value) {
    var source = '{{format x}}';
    var context = {x:value};
    var html = Handlebars.compile(source)(context);
    return new Handlebars.SafeString(html);
});
$(document).ready(function () {
    var source = $('#tmp').html();
    var template = Handlebars.compile(source);
    var html = template();
    $('#main').html(html);
});

输出:测试:2.33格式:2.33