John
John

Reputation: 351

What's wrong with this handlebars.js code?

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>

Upvotes: 1

Views: 1016

Answers (1)

Dennis
Dennis

Reputation: 14475

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>

Upvotes: 1

Related Questions