管理模板标记块的策略

时间:2014-11-28 19:31:48

标签: javascript jquery

我需要一种在我的脚本中管理HTML块的方法,因为我告诉我的方式太难以理解了。通常,我会写如下内容:

app.templates = (function () {
    return {
        status: '{0}<br />{1}',
        date: '{0} - {1}',
        details: '<li><i class="sprite"></i>{0} cart</li> \
                  <li><i class="sprite"></i>{1} total</li> \
                  <li><i class="sprite"></i>{2} items</li>'

然后,我会执行以下操作:$('.status').html(utls.format(app.templates.status, status));

我必须管理一些非常重要的模板块,有人能指出我更好的策略方向吗?

1 个答案:

答案 0 :(得分:0)

您可以采用knockout templates方法将它们放入类型为“text / html”的脚本标记中(浏览器会有效忽略它们)。然后,您可以进行关联查找并通过id获取模板标记。

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <style type="text/css">

        </style>
        <script type="text/javascript" 
 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.js">
        </script>
        <script type="text/html" id="foo">
            <div>here is some markup</div>
        </script>
        <script>
            $(function(){
                var templates={};
                $('head script[type="text/html"]')
                    .each(function(idx,scr){
                        var id = $(scr).attr("id");
                        var html = $(scr).html();
                        templates[id]=html;
                    });
                alert(templates["foo"]);
            });
        </script>
    </head>
    <body>
        woo-har!
    </body>
</html>
相关问题