如何将 jQuery.tmpl 模板呈现为字符串? [英] How do I render a jQuery.tmpl Template to a String?
问题描述
jquery.tmpl
的文档使用.appendTo
在渲染过程中将模板插入DOM:
The documentation for jquery.tmpl
uses .appendTo
to insert the template into the DOM during the rendering process:
$.tmpl( myTemplate, myData ).appendTo( "#target" );
我正在尝试从另一个模板引擎转换现有应用程序,并且我的代码需要先将模板呈现为字符串,然后再将其添加到 DOM.这可能吗?那要怎么做呢?
I am attempting to convert an existing app from another templating engine, and my code needs to render a template into a string first before it is added to the DOM. Is this possible? How would that be done?
推荐答案
jQuery Templating 提供 $.template()
(参见源代码中的描述) - 它在使用您的数据评估缓存模板后返回字符串数组.我是从头开始写的(以及在 Chrome 控制台中的实验),但你会明白整个想法.
jQuery Templating provides $.template()
(see description in source code) - it returns array of strings after evaluating cached template with your data. I am writing from scratch (and from experiments in Chrome's console), but you'll get the whole idea.
创建并缓存命名模板函数
Create and cache a named template function
$("template-selector").template("template-name");
获取您的模板函数并使用您的数据调用它
Get your template function and invoke it with your data
var tmpl = $.template("template-name"); // template function
var strings = tmpl($, {data: {<your data here>}}); // array of strings
var output = strings.join(''); // single string
这篇关于如何将 jQuery.tmpl 模板呈现为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!