什么'这个handlers.js代码有问题

What's wrong with this handlebars.js code?

本文关键字:js 代码 有问题 handlers 这个 什么      更新时间:2023-09-26

我有一个index.html,其中有这样的代码:我从handlebas网站上的文档中了解了它,但我无法使它工作。当我将字符串传递给var source时,它可以正常工作,但当我尝试使用$(#elem_id)获取模板时,handlers不会在其中插入数据。

<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>

我认为这是由您的HTML位于script标记中引起的。尝试将Html包装在一个不可见的div中(或者使div本身不可见),即:

<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>