官網:http://underscorejs.org/

因為之前用的 JS 樣版引擎 jQuery Template 已經停止更新很久很久了,
所以後來改用 Underscore 來當樣版引擎,以下是最簡單用法的筆記

請看程式

<script src='underscore-min.js'></script>
<script src='jquery.js'></script>
<script type="text/template" id="tmp_test">
    <div style='background:#EFE;'><%= name %></div>
</script>
<script type="text/template" id="tmp_test2">
    <ul>
        <% $.each(items, function(index, item){ %>
            <li><%= item %></li>
        <% }); %>
    </ul>
</script>
<script>
function add ()
{
    var a = _.template($('#tmp_test').html())({name:'leo'});
    $('#wrapper').append(a);
}
function add2 ()
{
    var a = _.template($('#tmp_test2').html())({items:[1,2,3,4]});
    $('#wrapper').append(a);
}
</script>
<input type='button' onclick='add()' value='add'>
<input type='button' onclick='add2()' value='add2'>
<div id='wrapper' style='background: #EEF; '></div>

後來覺得 Underscore 的 template 呼叫方式不太直覺,就寫了一個 jQuery Plugin 去包裝它
以下是程式

/**
 * Underscore Template Plugin
 * 因為覺得 Underscore 的呼叫很不直覺, 所以包成 jQuery 的 plugin
 * @author  Leo.Kuo <et282523@hotmail.com>
 * 
 * @example:  var _html = $('#template_name').(data);
 */
(function($, _)
{
    $.fn.template = function (data)
    {
        return _.template(this.html())(data);
    };
})(jQuery, _);
arrow
arrow
    全站熱搜

    wbkuo 發表在 痞客邦 留言(0) 人氣()