在客户端编译和呈现复杂的 Dust.js 模板
compiling and rendering complex Dust.js templates on the client
我正在尝试使用来自客户端的嵌套部分动态编译和渲染 Dust 模板,但我一直收到 "Error: Template Not Found: [templatePath]"。如果我使用不引用任何部分的子模板(例如 /templates/includes/childTemplate.dust),但不是来自更高级别的主模板(例如 /templates/main.dust),则下面显示的示例有效。有没有办法预编译包含子部分的高级模板?
var model = { ... };
$.get('/templates/main.dust', function(tpl) {
var compiled = dust.compile(tpl, 'mainTemplate');
dust.loadSource(compiled);
dust.render('mainTemplate', model, function(err, output) {
if (err) {
console.log(err);
}
$('#target').html(output);
});
});
灰尘部分在渲染时解决,而不是编译时,因此无法预编译到主模板中。
相反,Dust 提供了一种方法让您通过使用 dust.onLoad
函数告诉它如何加载其他模板。
dust.onLoad = function(templateName, callback) {
// naive jQuery loading of a new template
$.get('/templates/' + templateName + '.dust', function(data) {
callback(null, data);
});
};
如果收到模板后需要编译,将其作为第二个参数传给callback
,Dust会编译。如果您要加载预编译模板,只需调用 dust.loadSource(data)
评估预编译模板,然后调用 callback()
.
您可能希望在您的工作流程中加入模板预编译步骤,也许使用 Dust 中包含的 dustc
编译器,这样您就不必在客户端上编译(它很慢,你必须包括 dust-full.js
而不是 dust-core.js
).
您可以考虑将 Dust 及其模板加载为 AMD 模块。参见 http://www.dustjs.com/guides/setup/#amd 。如果您这样做,Dust 将使用 require
.
自动为您连接 onLoad
Dust 存储库有一些基本示例,说明您可以在浏览器中处理 Dust 的不同方式。参见 examples/basic-browser and examples/amd。
我正在尝试使用来自客户端的嵌套部分动态编译和渲染 Dust 模板,但我一直收到 "Error: Template Not Found: [templatePath]"。如果我使用不引用任何部分的子模板(例如 /templates/includes/childTemplate.dust),但不是来自更高级别的主模板(例如 /templates/main.dust),则下面显示的示例有效。有没有办法预编译包含子部分的高级模板?
var model = { ... };
$.get('/templates/main.dust', function(tpl) {
var compiled = dust.compile(tpl, 'mainTemplate');
dust.loadSource(compiled);
dust.render('mainTemplate', model, function(err, output) {
if (err) {
console.log(err);
}
$('#target').html(output);
});
});
灰尘部分在渲染时解决,而不是编译时,因此无法预编译到主模板中。
相反,Dust 提供了一种方法让您通过使用 dust.onLoad
函数告诉它如何加载其他模板。
dust.onLoad = function(templateName, callback) {
// naive jQuery loading of a new template
$.get('/templates/' + templateName + '.dust', function(data) {
callback(null, data);
});
};
如果收到模板后需要编译,将其作为第二个参数传给callback
,Dust会编译。如果您要加载预编译模板,只需调用 dust.loadSource(data)
评估预编译模板,然后调用 callback()
.
您可能希望在您的工作流程中加入模板预编译步骤,也许使用 Dust 中包含的 dustc
编译器,这样您就不必在客户端上编译(它很慢,你必须包括 dust-full.js
而不是 dust-core.js
).
您可以考虑将 Dust 及其模板加载为 AMD 模块。参见 http://www.dustjs.com/guides/setup/#amd 。如果您这样做,Dust 将使用 require
.
onLoad
Dust 存储库有一些基本示例,说明您可以在浏览器中处理 Dust 的不同方式。参见 examples/basic-browser and examples/amd。