3

I've been reading about the jQuery template plugin http://api.jquery.com/tmpl/ as a means of binding data to markup. All the examples seem to show that you define the template in a script new script tag. I'd actually prefer not to clutter my html <head> with all those script tags.

Is there a better way to organize this? Maybe with a templates folder full of scripts that get loaded dynamically?

4

2 回答 2

2

您可以将模板存储在外部文件中(例如,通过 Ajax 获取它们)。

引用自http://api.jquery.com/jQuery.template/

“...对于远程模板,您可以使用所需的任何 AJAX 调用将模板标记作为字符串获取,或者您可以简单地使用指向定义字符串的 js 文件的静态脚本块。然后您应该使用 jQuery.template从字符串编译模板,然后从那里开始,使用 jQuery.tmpl 渲染它”

于 2010-10-27T14:59:01.073 回答
2

你不必那样做。您可以(例如)将模板保存在 .js 文件中(有点像消息目录):

// this is a file full of templates
var SITE_TEMPLATES = {
  ERROR_1: 'This is an error template: the error is ${error.msg}',
  WHATEVER: 'I cannot make this stuff up but you get the ${idea}'
};

将其拉入,然后您可以通过以下方式使用模板

$('#someplace').append($.tmpl(SITE_TEMPLATES.ERROR_1, { error: { msg: "hello world" }}));

换句话说,$.tmpl()让您将模板主体作为第一个参数传入,它可以来自任何地方。

<script>或者,因为将长模板编写为 Javascript 字符串常量有点麻烦,您可以在单个静态 HTML 文件中堆积一堆文本标签。然后你可以 AJAX 并把它放在一个隐藏的地方<div>。这样您仍然可以获得缓存的优势,并且可能更容易维护模板。

当然,按照这些思路,您可以将模板作为单独的文件单独维护,并在站点构建时根据任何打包方案将它们粘合在一起。

于 2010-10-27T14:59:26.127 回答