What's wrong with this handlebars.js code?

爱⌒轻易说出口 提交于 2019-12-08 04:03:18

问题


I have an index.html where I have this code: I followed it from the documentation on handlebars site, but I am not able to make it work. When I pass a string to var source then it works fine, but when I try to get the template using $(#elem_id), handlebars does not insert the data in it.

<html>
<head>
<script src="../static/js/handlebars-1.0.0.beta.6.js"></script>
<script src="../static/jquery/1.7.1/jquery.js"></script>
</head>


<body>
    <script id="entry-template" type="text/x-handlebars-template">
     <div class="entry">
         <h1>{{title}}</h1>
         <div class="body">
            {{body}}
         </div>
    </div>
    </script>

    <script type="text/javascript">
        $(document).ready(function() {
            var source = $("#entry-template").html();
            var template = Handlebars.compile(source);
            var d = {"title": "My New Post", "body": "This is my first post!"};
            var result = template(d);
            console.log(result); //This just returns the template html, without the data
        });
    </script>


</body>
</html>

回答1:


I assume this is caused by your HTML being in script tags. Try wrapping your Html inside an invisible div (or make the div itself invisible), i.e.:

<div style='display:none;' id="entry-template" type="text/x-handlebars-template">
     <div class="entry">
         <h1>{{title}}</h1>
         <div class="body">
            {{body}}
         </div>
    </div>
</div>


来源:https://stackoverflow.com/questions/9972195/whats-wrong-with-this-handlebars-js-code

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