[英]render nunjucks template in the browser
最好的方法是使用自定義加載程序 。
首先,您將未渲染的模板發送給客戶端。 (您不需要預先呈現導入內容)然后編寫一個自定義加載程序,您可以在其中定義導入內容的加載方式。
示例(我使用type作為額外的GET參數來定義不應呈現模板):
var customLoader = {getSource:"",async:true};
customLoader.getSource = function(name, cb) {
var reqPath = window.location.protocol + "//" + window.location.host + "/" + name + "?type=view";
$.get(reqPath, (data) => {
cb(null, {src:data, path:reqPath});
});
}
var env = new nunjucks.Environment(customLoader);
然后,您可以使用env回調來呈現模板:
env.renderString(theInitialTemplate, yourJSONData, (err, res) => {
console.log(res); //do something with the res variable
});
在此示例中,我使用了異步加載程序。 您可以使用新的Promise加載模型和視圖,然后使用Promise.all進行檢查以將兩者放在一起並渲染模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.