我的模型的一些属性应该异步加载(由promises实现)。我不想等待它-我想现在就呈现它,并在promises将被解决时部分地更新它。handlebars.js是否支持它?
发布于 2016-11-22 17:30:27
Handlebar不支持异步。这使得在表达式和帮助器中使用Promises是不可能的。您可以使用await,但这会暂停执行,因此在Promise确定之前不会进行渲染。其他模板框架,如dust.js,提供了异步功能。
发布于 2021-05-01 05:21:50
我想我可以提出一个变通的办法,让异步(或承诺)工作(似乎)。下面是示例。基本上,这就是我正在做的事情。
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>https://stackoverflow.com/questions/17875667
复制相似问题