推荐的2012年jQuery模板?

时间:2012-12-27 22:55:40

标签: jquery html json templates

jQuery模板已经被弃用了一段时间。

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

  1. 我应该建立一个HTML字符串吗?
  2. 我应该通过jQuery创建元素,例如$('<li>',{id:'my-'+Id}).append($('<span>').text(myText))
  3. 是否有替代或成熟的jQuery模板替代品?

5 个答案:

答案 0 :(得分:104)

这就是我在项目中的表现:

在HTML中定义模板:

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

使用string.format替换变量:

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

非常简单,您甚至可以组合模板。

答案 1 :(得分:10)

您一定要尝试Handlebars和/或Mustache

我倾向于使用Handlebars,但语法非常相似。

答案 2 :(得分:9)

Mustache.js非常适合模板化。

https://github.com/janl/mustache.js

答案 3 :(得分:7)

模板一直比尝试手动解析JSON容易得多。由于我做出了贡献,我偏爱json2html,因为它不需要编译模板,只使用JSON和JavaScript。

http://json2html.com

答案 4 :(得分:0)

我真的不喜欢用javascript构建html元素所以我建议你使用一些模板 您可以找到模板列表和相关问题here

我过去常常使用jQuery Templates,这很简单但不再活跃。

相关问题