使用handlebar.js时,数据在浏览器上不可见

Thi*_*nan 0 handlebars.js

我正在为我的示例应用程序实现handlebar.js.根据handlebar.js文档,它尝试了所提到的示例.但是这些值会加载到脚本中的dom中,但在浏览器中不可见.

HTML

<body>
<h1>Handlebar</h1>
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>
</script>
<script  src="js/jquery-1.8.3.min.js"></script>
<script  src="js/handlebars.js"></script>
<script  src="js/app.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

app.js

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);
var context = {title: "My New Post", body: "This is my first post!"}
var html    = template(context);
$("#entry-template").html(template(context));
Run Code Online (Sandbox Code Playgroud)

当浏览器加载时,我得到一个空白的屏幕,但通过firebug调试时能够找到值标题和正文

mu *_*ort 6

您正在替换<script>元素的内容:

$("#entry-template").html(template(context));
Run Code Online (Sandbox Code Playgroud)

并且#entry-template<script>:

<script id="entry-template" type="text/x-handlebars-template">
Run Code Online (Sandbox Code Playgroud)

浏览器不会显示<script>s 的内容type.您希望将填好的模板放入<div>将要显示的模板中:

<h1>Handlebar</h1>
<div id="html-goes-here"></div>
Run Code Online (Sandbox Code Playgroud)

然后:

$("#html-goes-here").html(template(context));
Run Code Online (Sandbox Code Playgroud)