簡體   English   中英

使ust.js能夠呈現typeahead.js模板的最小干擾方式是什么?

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

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

現在ust.js在此問題上略有不同:

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

由於我已經集成了dust.js,因此我也想使用它來呈現typeahead的建議。 我可能可以包裝塵埃的引擎對象並提供所需的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')
)};

傳遞給typeahead插件的template參數可以是已編譯的模板或字符串。 如果是字符串,則typeahead插件將嘗試對其進行編譯。 不要用灰塵做這個。 相反,可以像通常一樣編譯塵土模板,但是將template參數傳遞為類似以下內容:

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

提前輸入應按原樣使用“已編譯”模板,而無需嘗試其他編譯。

編輯感謝@ user2103008,修復了灰塵渲染回調函數簽名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM