【发布时间】:2017-09-18 02:07:03
【问题描述】:
我正在使用车把模板。我偶然发现了一个奇怪的问题。以下代码在浏览器上使用时不会将上下文传递给已编译的车把模板,但奇怪的是相同的代码在 jsfiddle 中运行良好! https://jsfiddle.net/5pnfrjwa/
这是我的代码
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
{{> navbar this }}
<div id="render_here">
first
</div>
<div id="render_here_again">
second
</div>
<script id="first-template" type="text/x-handlebars-template">
<div>
<div> Inside first template</div>
<h4 style="color:green">title1 :{{title1}}</h4>
<h4 style="color:blue">body1 :{{body1}}</h4>
<h4 style="color:blue">context : {{context}}</h4>
</div>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js"></script>
<script>
$(document).ready(function() {
var source = $("#first-template").html();
var template = Handlebars.compile(source);
var context
// = "test 1"
= {
title1: "hello",
body1: "body1"
}
var el_html = template(context);
console.log("*** This is source : " + source);
console.log("*** This is template : " + template);
console.log("*** This is template(context) : " + el_html)
console.log(" data is : " + context.title1)
// $(document.body).append(el_html);
// $("#render_here").html(el_html);
// $("#render_here_again").html(el_html);
// document.getElementById('render_here_again').innerHTML = template(context);
$("#render_here_again").html(el_html)
});
</script>
</body>
</html>
我将源显示到控制台,这是输出
*** This is source :
<div>
<div> Inside first template</div>
<h4 style="color:green">title1 :</h4>
<h4 style="color:blue">body1 :</h4>
<h4 style="color:blue">context : </h4>
</div>
如果在jsfiddle上显示相同,则如下:
*** This is source :
<div>
<div> Inside first template</div>
<h4 style="color:green">title1 :{{title1}}</h4>
<h4 style="color:blue">body1 :{{body1}}</h4>
<h4 style="color:blue">context : {{context}}</h4>
</div>
似乎变量名称在 jsfiddle 上的双花括号中出现在源代码中,但它没有出现在我的语言环境机器上。知道为什么这在浏览器和 jsfiddle 上的行为不同。 我用 chrome 和 Mozilla 尝试过,但两者都面临同样的问题。 我在服务器端使用 nodejs 和 expressjs。
编辑一个 看来我可能已经确定了问题,但我仍在寻找解决方案。当我从 express 4 服务器呈现这些页面时,就会发生这种情况。如果我用上面的代码打开简单的 html 文件,它工作正常。
【问题讨论】:
标签: javascript html handlebars.js