0

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);

因为我已经集成了dust.js,所以我也想用它来呈现预先输入的建议。我可能可以包装灰尘的引擎对象并提供所需的 API,但我想知道是否有一种不那么侵入性和/或更优雅的方式来做到这一点,例如通过将所需的函数动态附加到灰尘对象本身?

编辑添加:混合 @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')
)};
4

1 回答 1

0

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

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,修复了灰尘渲染回调函数签名。

于 2013-10-11T09:51:37.063 回答