English 中文(简体)
How do I render a jQuery.tmpl Template to a String?
原标题:

The documentation for jquery.tmpl uses .appendTo to insert the template into the DOM during the rendering process:

$.tmpl( myTemplate, myData ).appendTo( "#target" );

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 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. Create and cache a named template function

    $("template-selector").template("template-name");
    
  2. 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
    
问题回答

The answers here didn t help me, however Adam s reply set me on the right track: any jQuery wrapped element has a .html() method.

var output = $( "#infoWindowTemplate" ).tmpl( city_data ).html()

or if you need text...

var output = $( "#infoWindowTemplate" ).tmpl( city_data ).text()

but please take note, that the outermost(root) element of the template is skipped, so you should make your templates look something like this:

  <script id= infoWindowTemplate  type= text/x-jquery-tmpl > 
    <div class= city_info >
      <h1 class= title ><a href="${link}">${name}</a></h1>
      <p class= meta >${count} offers</p>
    </div>
  </script> 

or just use the jQuery outerHtml plugin ( http://darlesson.com/jquery/outerhtml/ ) and replace .html() with .outerHTML()

You could do it by just putting the result in a temporary container and taking the innerHTML of it, like this:

var str = $("<div />").append($.tmpl(myTemplate, myData)).html();

jQuery.tmpl returns an HTMLElement wrapped in a jQuery object, which could be used in the same way as rendered strings were in the old template system.

var $template = $( #template ),
    html = $.tmpl($template, data).get();

I suspect that this might actually be faster than regular strings, but I don t have any profiling data for this yet.


Update

I did some basic profiling between Mustache.js and jQuery.tmpl, and the stats do not look good.

I started with 1,000 preloaded records and generated templates for them several times, averaging the results.

Mustache.js: 1783ms
jQuery.tmpl: 2243ms

I might wait until jQuery.tmpl closes that gap before switching.

This works correctly

    var s = $.tmpl(url, dataContext).get()[0].data;

I was wrong, above example works only if returned is somethig other that html. In case of html I use

    var s = $.tmpl(url, dataContext).get()[0].outerHTML

EDIT: After some digging I discovered diffrences between Chrome and FF (above examples works in Chrome).

Finally I found cross browser working method, lets assume that we like to build a tag. So we template will look like

    <a href= ${url} >${text}</a>

them simplest way to get resul as a string is to wrap template inside any tag and then use .html() function

    var t =  <div><a href= ${url} >${text}</a></div> 
    var d = {url:  stackoverflow.com , text:  best site };
    var html = $.tmpl(s, d).get()[0];
    html = $(html).html();  // trick is here

You can prepare template data like this

var tmplData = {link:"your link",name:"yourname",count:5};
$("#idofelementwhereuwanttoappend").append($("#infoWindowTemplate").tmpl(tmpldata));

This idofelementwhereuwanttoappend is id where your template data will be rendered.





相关问题
Check session from a view in CodeIgniter

What is the best way to check session from a view in CodeIgniter, it shows no way in their user guide, otherwise I will have to make two views on everything, which is kinda weird...still a newbie to ...

How to create a submit button template in Oracle APEX?

I m trying to create a template for a button in Oracle APEX but I don t seem to have access to the appropriate substitution strings to make it work. For non-templated buttons APEX seems to insert a ...

list of controls with templates in silverlight

Does anyone know where to find a list of controls that you can set the template on in Silverlight? I ve wasted several hours now trying to create control templates only to find that the control doesn ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Load ruby on rails template from database

I wonder if there is a way for me to store ruby on rails view files into database store and have that fetched directly from there. The reason is I want to create a CMS with all the user data stored in ...

Templated HTML Editor

I m looking for a HTML editor that kinda supports templated editing or live snippets or something like that. Background: I m working on a website for a friend. As there are no specifications what the ...

Dreamweaver changing path to site s reference instead of local

I have noticed recently, when I apply a template to a new HTML website, all the relative paths are pointed to my local files, example: file:///C|/webstuff/files but I cannot set them to relative paths ...

WPF ListView : Header styling

I want to have a ListView with columns and a particular style: The background for ALL column headers should be transparent except when the mouse is over in one of them. When this happends, the ...

热门标签