学会使用jquery tmpl从此不再痛苦的拼接html

学会使用jquery tmpl从此不再痛苦的拼接html

23600发表于2016-05-12


web开发经常会有用js动态生成html的时候,你在前台还在手动拼html吗?有的简单的html可以这样手动拼接,但是遇到比较复杂的,其中还有些逻辑判断的如果学是像以前一样的拼接,代码可读性和可维护性都会大打折扣。今天我介绍一个jquery的模板插件,学会使用jquery tmpl从此给拼接痛苦的html说再见。

$.tmpl( "<li>${Name}</li>", { "Name" : "John Doe" }).appendTo( "#target" );

jquery-tmpl 的github开源地址为:https://github.com/BorisMoore/jquery-tmpl

jQuery.tmpl() 有这些方法.appendTo, .prependTo, .insertAfter 和 .insertBefore

绑定本地数据

var movies = [
          { Name: "The Red Violin", ReleaseYear: "1998" },
          { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
          { Name: "The Inheritance", ReleaseYear: "1976" }
        ];

      var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

      // Compile the markup as a named template
      $.template( "movieTemplate", markup );

      // Render the template with the movies data and insert
      // the rendered HTML under the "movieList" element
      $.tmpl( "movieTemplate", movies )
          .appendTo( "#movieList" );


绑定远程数据

var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

    // Compile the markup as a named template
    $.template( "movieTemplate", markup );

    $.ajax({
      dataType: "jsonp",
      url: moviesServiceUrl,
      jsonp: "$callback",
      success: showMovies
    });

    // Within the callback, use .tmpl() to render the data.
    function showMovies( data ) {
      // Render the template with the "movies" data and insert
      // the rendered HTML under the 'movieList' element
      $.tmpl( "movieTemplate", data )
        .appendTo( "#movieList" );
    }


其它参数的使用:

var markup = "<li>Some content: ${$item.myMethod()}.<br/>" 
           + " More content: ${$item.myValue}.</li>";

    // Compile the markup as a named template
    $.template( "movieTemplate", markup );

    // Render the template with the movies data
    $.tmpl( "movieTemplate", movies,
      { 
          myValue: "somevalue", 
          myMethod: function() { 
              return "something";
          } 
      } 
    ).appendTo( "#movieList" );

下面我用的实际项目来说明一下jquery-tmpl的使用。
使用框架和技术
1、jquery1.6
2、jquery easyui
3、asp.net
最终的效果为:


注意:玩家和客服说的话是样式是不一样的,玩家那行没有背景颜色,我这里是用的css类来区分,当然你可以加更多的样式区别。

1、样式定义和模版插件引用

<style>
    .author{ padding-left:5px;width:50px;}
    .question{padding-left:10px; background-color:#FFFFFF; border:1px #8DB2E3 solid;}
    .answer{padding-left:10px;background-color:#EEEEFF; border:1px #8DB2E3 solid;}
</style>
<script src="/Scripts/jquery.tmpl.min.js" language="javascript" type="text/javascript"></script>
<script type="text/javascript" src="/Scripts/jquery-1.6.min.js"></script>

2、html代码


<div id="editWin">
        <table style=" padding-left:15px; width:98%;">
            <tr id="reply" style="margin-top:15px;">
                <td colspan="2">
                    <strong>客服回复</strong>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <textarea id="rContent" name="rContent" rows="9" cols="50"></textarea>
                </td>
            </tr>
           
            <tr>
                <td colspan="2">
                    <a href="#" class="easyui-linkbutton" onclick="save();return false;" iconcls="icon-save">
                        保存</a> <a href="#" class="easyui-linkbutton" onclick="cancel();return false;" iconcls="icon-undo">
                            取消</a>
                </td>
            </tr>
        </table>
</div>
最后要生成的html代码:
<div id="editWin">
        <table style="padding-left: 15px; width: 98%;">
            <tr data="history">
                <td class="author question">
                    玩家:
                </td>
                <td class="question">
                    2014-12-31 11:10:43:客服,我的刀爆了,怎么恢复????
                </td>
            </tr>
            <tr data="history">
                <td class="author question">
                    玩家:
                </td>
                <td class="question">
                    2015-01-04 16:38:32:999
                </td>
            </tr>
            <tr data="history">
                <td class="author question">
                    玩家:
                </td>
                <td class="question">
                    2015-01-04 16:40:42:亲爱的玩家朋友你好,针对你的问题我们的处理方式为xxxxxxxxxxxxxxxxxxxx,对你造成的不便请多多谅解,祝你游戏愉快!
                </td>
            </tr>
            <tr data="history">
                <td class="author answer">
                    客服:
                </td>
                <td class="answer">
                    2015-01-04 16:51:23:亲爱的玩家朋友你好
                </td>
            </tr>
            <tr id="reply" style="margin-top: 15px;">
                <td colspan="2">
                    <strong>客服回复</strong>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <textarea id="rContent" name="rContent" rows="9" cols="50"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <a href="#" class="easyui-linkbutton" onclick="save();return false;" iconcls="icon-save">
                        保存</a> <a href="#" class="easyui-linkbutton" onclick="cancel();return false;" iconcls="icon-undo">
                            取消</a>
                </td>
            </tr>
        </table>
</div>

3、定义模板

<script id="QATpl" type="text/x-jquery-tmpl">
     <tr data='history'>
        {{if Author=='玩家'}}
            <td class="author question">${Author}:</td>
            <td class="question">${CreateTime}:${Content}</td>
        {{else}}
            <td class="author answer">${Author}:</td>
            <td class="answer">${CreateTime}:${Content}</td>
        {{/if}}
        </tr>
</script>

4、ajax动态获取后台json数据

function edit(index, evt) {
            var rows = dgListEmail.datagrid('getRows'); 
            var row = rows[index];
            $.ajax({
                url: "?action=getEmailInfo",
                data: { cName: row.CharacterName, sName: row.ServerName },
                async: false,
                cache: false,
                dataType: 'json',
                type: "POST",
                success: function (data) {
                    $("#editWin table tr[data='history']").remove();
                    $("#QATpl").tmpl(data).insertBefore("#reply");
                    $('#editWin').window('open');
                }
});
服务端返回的data为:
[
  {
    "ServerName": "server1",
    "CreateTime": "2014-12-31 11:10:43",
    "Content": "客服,我的刀爆了,怎么恢复????",
    "CharacterName": "t",
    "Author": "玩家",
    "Title": "标题1"
  },
  {
    "ServerName": "server1",
    "CreateTime": "2015-01-04 16:38:32",
    "Content": "999",
    "CharacterName": "t",
    "Author": "玩家",
    "Title": ""
  },
  {
    "ServerName": "server1",
    "CreateTime": "2015-01-04 16:40:42",
    "Content": "亲爱的玩家朋友你好,针对你的问题我们的处理方式为xxxxxxxxxxxxxxxxxxxx,对你造成的不便请多多谅解,祝你游戏愉快!",
    "CharacterName": "t",
    "Author": "玩家",
    "Title": ""
  },
  {
    "ServerName": "server1",
    "CreateTime": "2015-01-04 16:51:23",
    "Content": "亲爱的玩家朋友你好",
    "CharacterName": "t",
    "Author": "客服",
    "Title": ""
  }
]

5、总结

学过mvc的同学应该可以看出上面的这种采用数据和html隔离开和mvc的model(模型(数据))和view(视图(html))分开一样大大地降低了两者之间的耦合性,如果以后想更改样式或者html只需要更改“第3点”中定义模板部分就可以了,而不需要眼睛都能看花的改拼接html字符串。jquery tmpl除了可以用if else,还可以each来遍历集合,可以模版调用子模版等等更加复杂的需求具体查看官方的demo。jquery tmpl更加详细的使用。


小编蓝狐