如何在javascript文件中编写把手模板

时间:2014-12-20 01:50:46

标签: javascript coding-style pug handlebars.js

javascript手柄模板通常会添加到HTML文件中,如果我们可以将所有模板保存在javascript文件中,那么这样做会更容易吗?

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

编辑:我也可以使用纯Javascript字符串编写此模板,还有其他选项吗?

var template = '<h1>{{title}}</h1>';

1 个答案:

答案 0 :(得分:0)

我认为你不能这样做。

因为浏览器执行的javascript是type="text/javascript",并且车把模板不应该在那里。

==编辑=======

为了使您的代码更清晰,您可以将把手模板放在另一个文件中。

这是一个例子:

test.php

<?php

?>

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js" ></script>

<script>
    (function(){
        $('body').load('assets/template.js', function(){
            var template = Handlebars.compile( $('#template').html() );
            var data = {
                'name': 'jone doe',
                'email': 'xx@example.com'
            };

            $('body').append( template(data) ); 
        });


    })()
</script>
</body>
</html>

assets/template.js

<script type="text/x-handlebars-template" id="template">
    {{name}}
    {{email}}
</script>