$.each & template

Template using jQuery:

<script id="blogTemplate" type="lines/template">
    <h2>{{title}}</h2>
    <img src={{thunbnail}} alt={{title}}/>
</script>
(function(){
     var content=[
      {
             title:"my first blog post",
             thunbnail:"https://tutsplus.s3.amazonaws.com/previewimages/nycmeetup.png",
          },
         {
             title:'my second blog post',
             thunbnail: 'http://d2o0t5hpnwv4c1.cloudfront.net/2053_userauth/Tutorial_preview.jpg',
          }
      ],
      template=$.trim($("#blogTemplate").html()) ;
                
      $.each(content,function(index,obj){
          var temp = template.replace(/{{title}}/ig,obj.title).replace(/{{thunbnail}}/ig,obj.thunbnail);

          $(document.body).append(temp);
     })
}());

 

and so if the content array contains more than 50 items ,and in the each method it will iterate over all these items,and as you can see, this will be so bad for the perfomance,so instead we will create another variable "flag" to get all the content in the array,when this step is finished,the put all of it into the DOM,

(function(){
    var content=[
        {
           title:"my first blog post",
           thunbnail:"https://tutsplus.s3.amazonaws.com/previewimages/nycmeetup.png",
          },
          {
            title:'my second blog post',
            thunbnail: 'http://d2o0t5hpnwv4c1.cloudfront.net/2053_userauth/Tutorial_preview.jpg',
          }
       ],
       template=$.trim($("#blogTemplate").html()),
       flag = '';
                
       $.each(content,function(index,obj){
       flag += template.replace(/{{title}}/ig,obj.title).replace(/{{thunbnail}}/ig,obj.thunbnail);                    
  })
  $(document.body).append(flag);
}());

 

jquery api for .each(): http://api.jquery.com/each/

juqey api for $.each(): http://api.jquery.com/jQuery.each/

 

 

Template using UnderscoreJs  

http://underscorejs.org/

<script type="text/template" id='template'>
    <h1><%= home %></h1>
</script>

underscore的template有两种写法: 

第一种:

    var tepl = _.template($('#template').html());
    var compile = tepl({'home':"do"});
    console.log(compile);

第一种显而易见是将script标签内的模板内容进行编译,返回一个function,然后再对值进行操作。返回的function如下:

    function (data) {
      return render.call(this, data, _);
    } 

第二种:

    var data = {'home':"myHome"};
    var template = _.template($('#template').html(),data);
    console.log(template)

直接传入值对填入选取到的模板

 

两种方法没区别,只是根据需要会用这个或者那个,其中还是使用jQuery作为DOM的选择器,”_.template()“属于

 

 

 

 

posted @ 2012-07-03 22:57  夹星蛋糕  阅读(201)  评论(0编辑  收藏  举报