How to insert JavaScript code in a Handlebars template?

拈花ヽ惹草 提交于 2020-08-05 06:19:57

问题


Quoting Handlebars 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>

As you can see no Yay! is alerted.

How to make this work?


回答1:


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.

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>


来源:https://stackoverflow.com/questions/45580162/how-to-insert-javascript-code-in-a-handlebars-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!