制造灰尘的侵入性最小的方法是什么.js能够提前渲染打字.js模板

What's the least intrusive way to make dust.js able to render typeahead.js templates?

本文关键字:js 模板 是什么 方法 制造      更新时间:2023-09-26

typeahead.js 使我们能够使用我们选择的引擎为我们的自动完成建议呈现模板,只要引擎实现了这个 API:

// engine has a compile function that returns a compiled template
var compiledTemplate = ENGINE.compile(template);
// compiled template has a render function that returns the rendered template
// render function expects the context to be first argument passed to it
var html = compiledTemplate.render(context);

现在Dust.js对此事的看法略有不同:

var compiled = dust.compile("Hello {name}!", "intro");
dust.loadSource(compiled);

由于我已经集成了灰尘.js我也想使用它来渲染 typeahead 的建议。我可能可以包装 dust 的引擎对象并提供所需的 API,但我想知道是否有一种侵入性更小和/或更优雅的方式来做到这一点,例如通过将所需的功能动态附加到 dust 对象本身?

编辑添加:混合@user2103008和@Simon所拥有的东西,这是我在 typeahead-0.9.3 中使用的内容:

function typeaheadFakeCompile(dustTemplateName) {
    return function(data) {
        var html;
        dust.render(dustTemplateName, data, function(err, out) { html = out; })
        return html;
    }
}
var compiled = dust.compile('Hello {name}!', 'myTemplate');
dust.loadSource(compiled);
$('selector').typeahead({
   template: typeaheadFakeCompile('myTemplate')
)};

传递给 typeahead 插件的 template 参数可以是编译的模板或字符串。如果它是一个字符串,则预类型插件将尝试编译它。不要用灰尘做这件事。相反,像往常一样编译 dust 模板,但将模板参数传递为如下所示:

var compiled = dust.compile('Hello {name}!', 'myTemplate');
dust.loadSource(compiled);
$('selector').typeahead({
    template: fakeCompile('myTemplate')
)};
function fakeCompile (dustTemplateName) {
    return {
        render: function (data) {
            var html;
            dust.render(dustTemplateName, data, function (err,out) { html = out });
            return html;
        }
    }
}

Typeahead 应按原样使用"已编译"模板,而无需尝试其他编译。

编辑得益于@user2103008,修复了灰尘渲染回调函数签名。