我正在尝试为客户端HTML/JS模板系统编写一个适配器,以便在幕后使用dust.js。不幸的是,API期望呈现操作同步发生:呈现的输出应该从render()调用中返回。Dust.js是异步的,并将呈现输出传递给回调函数。有没有办法解决这个问题,无论是在Dust API中还是通过一些疯狂的Javascript黑客?
发布于 2012-05-02 12:25:06
如果在执行模板之前加载了模板的所有依赖项,那么它将同步执行(据我所知)。所以你可以这样做:
var result;
dust.render("tpl", data, function(err, res) {
result = res;
});
console.log(result); // result will actually already be filled out if dustjs didn't
// have to go look for resources somewhere.<script type="text/javascript" src="dust.js"></script>
<script>
var tpl = dust.compile("Omg {#people} {.} {/people} are here! {>partial/}", "tpl");
var partial = dust.compile("I'm a partial but I've already been included so things still run {how}", "partial");
dust.loadSource(tpl);
dust.loadSource(partial);
var data = {
people: ["jim", "jane", "jack", "julie"],
how: "synchronously!"
};
var result;
dust.render("tpl", data, function(err, res) {
result = res;
});
console.log(result);
</script>可能会有我错的情况(除了我提到的那个)。我不知道关于灰尘的一切。
发布于 2012-12-01 05:16:54
我也希望有一个接受上下文并返回灰尘渲染文本的函数。这是我想出的解决方案:
// This function sets up dust template, and returns a new function "dusterFn()"
// dusterFn() can be passed a Context, and will return the rendered text.
// @param {String} text: The template text.
// @param {String} [name]: The name of the template to register with dust. If none is provided, a random number is used.
// @param {Function} [onError]: A function that is called if an error occurs during rendering.
function getDusterFn(text, name, onError) {
var dusterFn = null;
name = name || Math.floor(Math.random() * 99999).toString();
onError = onError || function (error) { };
try {
var compiled = dust.compile(text, name)
dust.loadSource(compiled);
dusterFn = function (context) {
var dustOutput = '';
dust.render(name, context, function (error, out) {
if (error) onError(error);
dustOutput = out;
});
return dustOutput;
};
} catch (e) {
// invalid template syntax
e += "\n\nPlease check your template syntax.";
throw (e);
}
return dusterFn;
}使用
var greetingTemplate = getDusterFn('Hello {name}, You are {age} years old!');
greetingTemplate({name: 'Jane', age: 24});发布于 2015-05-22 14:08:59
Matt的解决方案给了我一些指导,告诉我如何编写一个小包装器来隐藏他的解决方案的“丑陋”(所谓“丑陋”,我指的是在回调之外声明变量,在回调内赋值,以及在回调外返回)。
它不仅将hack封装到一个小函数中,还绑定了模板的名称。
function templates(template) {
return function templatesWrapper(data) {
var result;
dust.render(template, data, function onRender(err, data) {
if (err) {
throw err;
}
result = data;
});
return result;
}
}下面是它的使用方法:
var renderHello = templates('hello.html');
renderHello({ username: 'Stackoverflow' });
// => <h1>Hello, Stackoverflow</h1>https://stackoverflow.com/questions/9848851
复制相似问题