2012年推荐的jQuery模板? [英] Recommended jQuery templates for 2012?

查看:85
本文介绍了2012年推荐的jQuery模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery模板已经过时了一段时间.

jQuery Templates have been deprecated for some time now.

我有一些JavaScript对象形式的数据,我想将其格式化为HTML并附加到DOM.这些天最好的方法是什么?

I have some data in the form of a JavaScript object that I want to format as HTML and append to the DOM. What's the best way of doing that these days?

  1. 我应该建立一个HTML字符串吗?
  2. 我是否应该通过jQuery创建$('<li>',{id:'my-'+Id}).append($('<span>').text(myText))之类的元素?
  3. 是否有jQuery模板的替代品或成熟替代品?
  1. Should I build up an HTML string?
  2. Should I create elements via jQuery such as $('<li>',{id:'my-'+Id}).append($('<span>').text(myText)) ?
  3. Is there a replacement or mature substitute for jQuery templates?

推荐答案

这是我在项目中的做法:

This is how I do it in my projects:

在HTML中定义模板:

Define a template in your HTML:

<script type="text/template" id="cardTemplate">
<div>
    <a href="{0}">{1}</a>
</div>
</script>

使用string.format替换变量:

Use string.format to substitute variables:

var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);

string.format :

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

非常简单,您甚至可以合并模板.

Pretty simple, you can even combine templates.

这篇关于2012年推荐的jQuery模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆