笔记:$.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: "http://placehold.it/150x150"
    },
    {
      title: "my second blog post",
      thunbnail: "http://placehold.it/150x150"
    }
  ],
  template = $.trim($("#blogTemplate").html());

  $.each(content, function(index, obj) {
    var temp = template
      .replace(/{{title}}/gi, obj.title)
      .replace(/{{thunbnail}}/gi, 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}}/gi, obj.title)
      .replace(/{{thunbnail}}/gi, obj.thunbnail);
  });
  $(document.body).append(flag);
})();

demo

See the Pen 笔记:$.each() & template by Lien (@movii) on CodePen.



Template using UnderscoreJs

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

第一种

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);

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

感谢阅读

你们好, 2018 年初把小站从 Jekyll 迁移到 Hugo 的过程中,删除了评论区放的 Disqus 插件,考虑有二:首先无论评论、还是对笔记内容的进一步讨论,读者们更喜欢通过邮件、或者 Twitter 私信的方式来沟通;其次一年多以来 Disqus 后台能看到几乎都是垃圾留言(spam),所以这里直接贴一下邮件、以及 Twitter 账户 地址。

技术发展迭代很快,所以这些笔记内容也有类似新闻的时效性,不免有过时、或者错误的地方,欢迎指正 ^_^。

BEST
Lien(A.K.A 胡椒)
本站总访问量 本站总访客量 本文总阅读量