Is it possible to define a view template in a javascript variable, instead of a script tag or a file?
Something like this:
var template = "< h1 ><%= title %> < / h1 >";
var rendered = can.view.render(template, data);
Is it possible to define a view template in a javascript variable, instead of a script tag or a file?
Something like this:
var template = "< h1 ><%= title %> < / h1 >";
var rendered = can.view.render(template, data);
Take a look to jquery utils string format plugin. There is an example that shows rendering html from template that was defined as as string.
Creating template:
$.tpl('tweet', [
'<div id="tweet-{id:s}" class="tweet">',
'<div class="tweet-body"><b>@{from:s}</b>: {body:s}',
'(<a href="{href:s}" class="tweet-date">',
'<abbr title="{timestamp:s}">{timesince:s}</abbr>',
'</a>)',
'</div>',
'</div>'
]);
Rendering:
$.getJSON('/tweets/username/', function(resp, s){
$.each(resp.tweets, function(idx, tweet) {
$.tpl('tweet', {
id: tweet.id,
body: tweet.body,
from: tweet.screen_name,
timestamp: tweet.pub_time,
timesince: $.timeago(tweet.pub_time)
}).appendTo('#tweet-list');
});
});
Ok, after a lot of research, because it isn't written in documentation, I found how to do it. The trick is that you have to register your template with an id first. If you are using a script tag or url to find a template, this step is done automatically by canJS.
So, if you want to render a template, stored in a variable, you have to do something like this:
Now you have the document fragment in
rendered
.