如何将jQuery.tmpl模板呈现为字符串? [英] How do I render a jQuery.tmpl Template to a String?

查看:558
本文介绍了如何将jQuery.tmpl模板呈现为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()

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.

  1. 创建并缓存命名模板函数

  1. 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆