在浏览器中渲染 nunjucks 模板
render nunjucks template in the browser
nunjucks 模板的一部分包含我想在页面发送到浏览器后设置的变量。目前它还需要 import 其他模板。
我需要预先包含其他 imported 模板吗?
最好的方法是使用 custom loader.
首先,您将未呈现的模板发送给客户端。 (您不需要预呈现导入)然后编写一个自定义加载程序,您可以在其中定义应如何加载导入。
示例(我使用类型作为额外的 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 检查以将两者放在一起并呈现模板。
nunjucks 模板的一部分包含我想在页面发送到浏览器后设置的变量。目前它还需要 import 其他模板。
我需要预先包含其他 imported 模板吗?
最好的方法是使用 custom loader.
首先,您将未呈现的模板发送给客户端。 (您不需要预呈现导入)然后编写一个自定义加载程序,您可以在其中定义应如何加载导入。
示例(我使用类型作为额外的 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 检查以将两者放在一起并呈现模板。