2012 年推荐的 jQuery 模板?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14062368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recommended jQuery templates for 2012?
提问by mpen
jQuery Templates have been deprecated for some time now.
jQuery 模板已经被弃用一段时间了。
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?
我有一些 JavaScript 对象形式的数据,我想将其格式化为 HTML 并附加到 DOM。现在最好的方法是什么?
- Should I build up an HTML string?
- Should I create elements via jQuery such as
$('<li>',{id:'my-'+Id}).append($('<span>').text(myText))
? - Is there a replacement or mature substitute for jQuery templates?
- 我应该建立一个 HTML 字符串吗?
- 我应该通过 jQuery 创建元素
$('<li>',{id:'my-'+Id}).append($('<span>').text(myText))
吗? - 是否有 jQuery 模板的替代品或成熟的替代品?
回答by sachleen
This is how I do it in my projects:
这就是我在我的项目中的做法:
Define a template in your HTML:
在 HTML 中定义模板:
<script type="text/template" id="cardTemplate">
<div>
<a href="{0}">{1}</a>
</div>
</script>
Use string.format to substitute variables:
使用 string.format 替换变量:
var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);
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.
非常简单,您甚至可以组合模板。
回答by Antonio Laguna
You should definitely try Handlebarsand/or Mustache
你绝对应该尝试Handlebars和/或Mustache
I tend to use Handlebars but the syntax is quite similar.
我倾向于使用 Handlebars,但语法非常相似。
回答by Joe
回答by Chad Brown
Templates all the way, so much easier than trying to parse the JSON manually. Since I contributed to it, I'm partial to json2html as it doesn't require compiling of the templates AND uses nothing but JSON and JavaScript.
一路模板,比尝试手动解析 JSON 容易得多。由于我对它做出了贡献,因此我偏爱 json2html,因为它不需要编译模板并且只使用 JSON 和 JavaScript。
回答by Ricardo Alvaro Lohmann
I realy don't like to build html element using javascript so I suggest you to use some template.
You can find a list of templates and a related question here.
我真的不喜欢使用 javascript 构建 html 元素,所以我建议你使用一些模板。
您可以在此处找到模板列表和相关问题。
I used to use jQuery Templates
, it's prety simple but it's no longer actively.
我曾经使用过jQuery Templates
,它很简单,但不再主动了。