jquery 模板
jQuery 模板
jQuery 模板是一种基于 jQuery 的数据绑定和渲染技术,通常用于动态生成 HTML 内容。以下是一些常见的 jQuery 模板实现方式:
使用 $.tmpl()(官方插件)
jQuery 官方曾推出 jquery.tmpl 插件,但目前已不再维护。其基本语法如下:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/tmpl/1.4.1/jquery.tmpl.min.js"></script>
<script id="template" type="text/x-jquery-tmpl">
<li>${name} (${age})</li>
</script>
<script>
const data = [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }];
$("#template").tmpl(data).appendTo("ul");
</script>
使用字符串拼接
对于简单场景,可以直接拼接字符串生成 HTML:
const data = [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }];
let html = "";
$.each(data, function(index, item) {
html += `<li>${item.name} (${item.age})</li>`;
});
$("ul").html(html);
使用第三方模板引擎
现代开发中更推荐使用专门的模板引擎(如 Handlebars、Mustache 等)与 jQuery 结合:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
{{#each this}}
<li>{{name}} ({{age}})</li>
{{/each}}
</script>
<script>
const template = Handlebars.compile($("#template").html());
const data = [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }];
$("ul").html(template(data));
</script>
使用 ES6 模板字符串
现代浏览器支持直接使用 ES6 模板字符串:

const data = [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }];
const html = data.map(item => `<li>${item.name} (${item.age})</li>`).join("");
$("ul").html(html);
选择建议
- 简单项目:字符串拼接或 ES6 模板字符串
- 复杂模板:Handlebars/Mustache 等专业引擎
- 旧代码维护:
$.tmpl()(需注意兼容性)
所有方法均需确保数据已正确转义,防止 XSS 漏洞。






