Working with Handlebar.js

寵の児 提交于 2019-12-23 09:04:48

问题


I was actually trying to find some tutorials on Handlebar.js & I found this http://javascriptplayground.com/blog/2012/05/javascript-templating-handlebars-tutorial

But it is not actually working as expected.

What I am doing is I have an index.html file,

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js" type="text/javascript" charset="utf-8"></script>
        <script src="app.js" type="text/javascript" charset="utf-8"></script>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Messing with Handlebars</title>

    </head>
    <body>
        <script id="ajax-comment" type="text/x-handlebars-template">
            <li>
            <span class="meta">{{name}} on {{date}}</span>
            <p>{{comment}}</p>
            </li>
        </script>

    </body>
</html>

and an app.js which contains the code.

var source = $("#ajax-comment").html();
var template = Handlebars.compile(source);
var data = {
    name : "Jack",
    date : "12/04/12",
    comment : "This is a really awesome tutorial. Thanks."
};
$("ul").append(template(data)); 

But all I am getting is a blank page. Any mistake I am making here? Detailed explanations would be helpful.


回答1:


"ul" element doesn't exist, you must append it to something which actually exists.

just add a <ul></ul> somewhere in the body.

fiddle here




回答2:


You might want to check the answer to this question Seems like the jquery function was not able to access the element since the DOM wasnt loaded before the call was made. I tried some more combinations after the initial changes of calling the app.js code(without wrapping it inside a function) only after the DOM was loaded which worked. For example I moved the script call just before the </body> which worked too.

... <script src="app.js" type="text/javascript" charset="utf-8"></script> </body>

It also helped me to know whether we use HTML or XHTML as our document type, to understand this problem better.




回答3:


try putting ref to your external JS at bottom, just above the closing body tag

eg

<body>
    <ul></ul>
   <!-- last thing on the page--> 
   <script src="app.js" type="text/javascript"></script>
</body>

this seemed to have solved it for me



来源:https://stackoverflow.com/questions/12268088/working-with-handlebar-js

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