如何在Handlebars模板中插入JavaScript代码? [英] How to insert JavaScript code in a Handlebars template?
问题描述
引用车把FAQ:
如何在模板中包含脚本标签?
How can I include script tags in my template?
如果通过内联标签加载模板,则可能需要使用空注释将脚本标签拆分,以避免浏览器解析器错误:
If loading the template via an inlined tag then you may need to break up the script tag with an empty comment to avoid browser parser errors:
<script type="text/x-handlebars">
foo
<scr{{!}}ipt src="bar"></scr{{!}}ipt>
</script>
尽管如此,我似乎无法实现此目标:
Nevertheless, I can't seem to be able to implement this:
document.getElementById('output').innerHTML =
Handlebars.compile(
document.getElementById("template").innerHTML
)({});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.js"></script>
<script id="template" type="text/x-handlebars">
foo
<scr{{!}}ipt>
alert("Yay!");
</scr{{!}}ipt>
</script>
<div id="output"></div>
您可以看到没有Yay!
警报.
如何进行这项工作?
推荐答案
我使用jQuery的.html()
尝试了相同的方法,并且效果很好.当我查看此时,我可以确定罪魁祸首是.innerHTML
答案.
I tried the same with jQuery's .html()
and it worked fine. I could narrow down on .innerHTML
being the culprit when I looked into this answer.
简而言之,需要使用eval()
明确评估插入.innerHTML
的script
标签.
In short, script
tags inserted with .innerHTML
needs to be explicitly evaluated using eval()
.
因此,如果您评估脚本,以下代码将起作用:
So below code works, if you eval the script:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("output").innerHTML = (Handlebars.compile(
document.getElementById("template").innerHTML
))({});
eval(document.getElementById("myscript").innerHTML); // explicitly eval the script
}, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.js"></script>
<script id="template" type="text/x-handlebars">
foo
<scr{{!}}ipt id="myscript" src="bar">console.log("Hello")</scr{{!}}ipt>
</script>
<div id="output"></div>
这篇关于如何在Handlebars模板中插入JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!