[英]Does handlebars.js support promises?
我的模型的某些属性应该异步加载(由承诺实现)。 我不想等待 - 我想立即渲染它并在承诺解决时部分更新它。 handlebars.js 支持吗?
把手不支持异步。 这使得无法将 Promise 用于表达式和助手。 您可以使用await
但这会暂停执行,因此在 Promise 解决之前不会进行渲染。 其他模板框架(如dust.js)提供异步功能。
我想我可以提出一种解决方法来使异步(或承诺)(似乎)起作用。 下面是示例。 基本上这就是我正在做的
unique Id
的 div(我在这里使用命名空间 + 自动增量)unique id
访问它,用新数据替换 step1 中 div 的 innerHTML 下面的代码。 观察三重括号 ( {{{ }}}
)。 这是为了确保生成的 HTML 不会被转义
<script id="handlebars-demo" type="text/x-handlebars-template">
<div>
-->> {{{functionName "functionParam" }}} <<--
</div>
</script>
<div id="output" />
<script>
window.id=0;
Handlebars.registerHelper('functionName', function(funcParam ){
let tempId = "my_namespace_" + window.id++;
$.post("https://something.com/abc").done(function(data){
$("#"+tempId ).html(data.something);
}
)
return '<div id='+tempId+'>loading</div>'
});
var template = document.getElementById("handlebars-demo").innerHTML;
var templateScript = Handlebars.compile(template);
var context = { };
var html = templateScript(context);
document.getElementById("output").innerHTML= html;
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.