问题描述
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模板提供$.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模板呈现为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!