jQuery.View class
plugin: jquery/view
download: jQuery.View
test: qunit.html
View provides a uniform interface for using templates with jQuery. Whentemplate engines registerthemselves, you are able to:
The GetStarted with jQueryMX has a good walkthrough of $.View.
Use
When using views, you're almost always wanting to insert the results of arendered template into the page. jQuery.View overwrites the jQuery modifiers sousing a view is as easy as:
$("#foo").html('mytemplate.ejs',{message: 'hello world'})
This code:
<h2><%= message%></h2>
<divid='foo'>"<h2>hello world</h2></div>
<div id='foo'><h2>hello world</h2></div>
jQuery Modifiers
You can use a template with the following jQuery modifiers:
$('#bar').after('temp.jaml',{}); | |
$('#bar').append('temp.jaml',{}); | |
$('#bar').before('temp.jaml',{}); | |
$('#bar').html('temp.jaml',{}); | |
$('#bar').prepend('temp.jaml',{}); | |
$('#bar').replaceWith('temp.jaml',{}); | |
$('#bar').text('temp.jaml',{}); |
You always have to pass a string and an object (or function) for thejQuery modifier to user a template.
Template Locations
View can load from script tags or from files.
From Script Tags
To load from a script tag, create a script tag with your template and anid like:
<script type='text/ejs' id='recipes'>
<% for(var i=0; i < recipes.length; i++){ %>
<li><%=recipes[i].name %></li>
<%} %>
</script>
Render with this template like:
$("#foo").html('recipes',recipeData)
Notice we passed the id of the element we want to render.
From File
You can pass the path of a template file location like:
$("#foo").html('templates/recipes.ejs',recipeData)
However, you typically want to make the template work from whatever pagethey are called from. To do this, use // to look up templates from JMVC root:
$("#foo").html('//app/views/recipes.ejs',recipeData)
Finally, the controller/viewplugin can make looking up a thread (and adding helpers) even easier:
$("#foo").html( this.view('recipes', recipeData) )
Packaging Templates
If you're making heavy use of templates, you want to organize them infiles so they can be reused between pages and applications.
But, this organization would come at a high price if the browser has toretrieve each template individually. The additional HTTP requests would slowdown your app.
Fortunately, [steal.static.views steal.views] can build templates intoyour production files. You just have to point to the view file like:
steal.views('path/to/the/view.ejs');
Asynchronous
By default, retrieving requests is done synchronously. This is finebecause StealJS packages view templates with your JS download.
However, some people might not be using StealJS or want to delay loadingtemplates until necessary. If you have the need, you can provide a callbackparamter like:
$("#foo").html('recipes',recipeData, function(result){
this.fadeIn()
});
The callback function will be called with the result of the renderedtemplate and 'this' will be set to the original jQuery object.
Deferreds (3.0.6)
If you pass deferreds to $.View or any of the jQuery modifiers, the viewwill wait until all deferreds resolve before rendering the view. This makes ita one-liner to make a request and use the result to render a template.
The following makes a request for todos in parallel with the todos.ejstemplate. Once todos and template have been loaded, it with render the viewwith the todos.
$('#todos').html("todos.ejs",Todo.findAll());
Just Render Templates
Sometimes, you just want to get the result of a rendered template withoutinserting it, you can do this with $.View:
var out = $.View('path/to/template.jaml',{});
Preloading Templates
You can preload templates asynchronously like:
$.get('path/to/template.jaml',{},function(){},'view');
Supported Template Engines
JavaScriptMVC comes with the following template languages:
<h2><%= message%></h2>
h2(data.message);
<h2>{%= message%}</h2>
<h2>${message}</h2>
The popular Mustachetemplate engine is supported in a 2nd party plugin.
Using other Template Engines
It's easy to integrate your favorite template into $.View and Steal. Readhow in jQuery.View.register.
Constructor
Looks up a template, processes it, caches it, then renders the template withdata and optional helpers.
With StealJS,views are typically bundled in the production build. This makes it ok to useviews synchronously like:
$.View("//myplugin/views/init.ejs",{message: "HelloWorld"})
If you aren't using StealJS, it's best to use views asynchronously like:
$.View("//myplugin/views/init.ejs",
{message: "Hello World"}, function(result){
// do something with result
})
new $.View(view, data, helpers, callback) -> String
view {String}
The url or id of an element to use as the template's source.
data {Object}
The data to be passed to the view.
helpers {optional:Object}
Optional helper functions the view might use. Not all templates supporthelpers.
callback {optional:Object}
Optional callback function. If present, the template is retrievedasynchronously. This is a good idea if you aren't compressing the templatesinto your view.
returns {String}
The rendered result of the view or if deferreds are passed, a deferredthat will resolve to the rendered result of the view.
jQuery 1.6 brought Deferred support.They are a great feature that promise to make a lot of asynchronousfunctionality easier to write and manage. jQuery.View uses Deferreds tosimplify a common but annoying task into a one-liner: loading data and atemplate and rendering the result into an element.
Here's what rendering templates looks like with deferreds:
$(
'#todos').html(
'temps/todos.ejs', $.get(
'/todos',{},
'json') );
This will make two parallel ajax requests. One request ismade for the template at temps/todos.ejs
:
<%
for(
vari =
0; i <
this.length; i++) { %>
<li><%=
this[i].name %></li>
<% } %>
The second request for /todos
might respondwith a JSON array:
[
{
"id":
1,
"name":
"Take out the Trash"},
{
"id":
2,
"name":
"Do the Laundry"}
]
When both have been loaded, the template is rendered withthe todos data. The resulting HTML is placed in the #todos
element.
This is fab fast! The AJAX and template request are made inparallel and rendered when both are complete. Before deferreds, this was a lotuglier:
var template,
data,
done =
function(){
if
( template && data ) {
var
html =
newEJS({text: template})
.render(data);
$(
'#todos').html( html )
}
}
$.get(
'temps/todos.ejs',
function(text){
template = text;
done();
},
'text')
$.get(
'/todos',{},
function(json){
data = json
done();
},
'json')
Model AJAX functions now return deferreds. Creating modelslike:
$.Model(
'User',{
findAll:
'/users'
},{});
$.Model(
'Todo',{
findAll:
'/todos'
},{})
Lets you request todos and users and get back a deferredthat can be used in functions that accept deferreds like $.when:
$.when( User.findAll(),
Todo.findAll() )
Or $.View:
$(
'#content').html(
'temps/content.ejs',{
users : User.findAll(),
todos: Todo.findAll()
})
Jaml class
plugin: jquery/view/jaml
Jaml is a simple JavaScript library which makes HTML generation easy andpleasurable.
Instead of magic tags, Jaml is pure JS. It looks like:
function(data) {
h3(data.message);
}
Jaml is integrated into jQuery.View so you can use it like:
$("#foo").html('//app/views/template.jaml',{});
Use
For more info check out:
· Jaml.register function
· Source
· Registers atemplate by name
· API
· Jaml.register(name, template) -> undefined
· name {String}
· The name of thetemplate
· template {Function}
· The templatefunction
· returns {undefined}
· Jaml.registerHelper function
· Source
· Registers a helperfunction
· API
· Jaml.registerHelper(name, helperFn) -> undefined
· name {String}
· The name of thehelper
· helperFn {Function}
· The helper function
· returns {undefined}
· Jaml.render function
· Source
· Renders the giventemplate name with an optional data object
· API
· Jaml.render(name, data) -> undefined
· name {String}
· The name of thetemplate to render
· data {Object}
· Optional dataobject
· returns {undefined}
plugin: jquery/view/ejs
download: jQuery.EJS
test: qunit.html
Ejs provides ERB style clientside templates. Use them with controllers to easily build html and inject itinto the DOM.
The following generates a list of tasks:
<ul>
<% for(var i = 0; i < tasks.length; i++){ %>
<li class="task <%= tasks[i].identity %>"><%= tasks[i].name %></li>
<% } %>
</ul>
For the following examples, we assume this view is in 'views\tasks\list.ejs'.
You should use EJS through the helper functions jQuery.Viewprovides such as:
or jQuery.Controller.prototype.view.
EJS uses 5 types of tags:
· <% CODE %>
- Runs JS Code. For example:
·
<% alert(
'hello world') %>
· <%= CODE %>
- Runs JS Code and writes the escaped result into the result of thetemplate. For example:
·
<h1><%=
'hello world'%></h1>
· <%== CODE %>
- Runs JS Code and writes the unescaped result into the result of thetemplate. For example:
·
<h1><%==
'<span>hello world</span>'%></h1>
· <%%= CODE %>
- Writes <%= CODE %> to the result of the template. This isvery useful for generators.
·
<%%=
'hello world'%>
· <%# CODE %>
- Used for comments. This does nothing.
·
<%#
'hello world'%>
After drawing some html, you often want to add otherwidgets and plugins inside that html. View makes this easy. You just have toreturn the Contoller class you want to be hooked up.
<ul <%= Mxui.Tabs%>>...<ul>
You can even hook up multiple controllers:
<ul <%= [Mxui.Tabs, Mxui.Filler]%>>...<ul>
To hook up a controller with options or any other jQueryplugin use the pluginview helper:
<ul <%= plugin(
'mxui_tabs', { option:
'value'}) %>>...<ul>
Don't add a semicolon when using view helpers.
View Helpers return html code. View by default only comeswith viewand [jQuery.EJS.Helpers.prototype.text text]. You can include more with theview/helpers plugin. But, you can easily make your own! Learn how in the Helperspage.
Creates a new view
new $.EJS(options) -> jquery.ejs
{Object}
A hash with the following options
Option | Default | Description |
text |
| uses the provided text as the template. Example: |
type | '<' | type of magic tags. Options are '<' or '[' |
name | the element ID or url | an optional name that is used for caching. |
{jquery.ejs}
jQuery.EJS.Helpers class
By adding functions to jQuery.EJS.Helpers.prototype, those functions willbe available in the views.
The following helper converts a given string to upper case:
$.EJS.Helpers.prototype.toUpper =function(params)
{
return params.toUpperCase();
}
Use it like this in any EJS template:
<%= toUpper('javascriptmvc') %>
To access the current DOM element return a function that takes the elementas a parameter:
$.EJS.Helpers.prototype.upperHtml= function(params)
{
return function(el) {
$(el).html(params.toUpperCase());
}
}
In your EJS view you can then call the helper on an element tag:
<div <%= upperHtml('javascriptmvc') %>></div>
Constructor
Creates a view helper. This function is called internally. You shouldnever call it.
new $.EJS.Helpers(data) -> jquery.ejs.helpers
data {Object}
The data passed to the view. Helpers have access to it through this._data
returns {jquery.ejs.helpers}
jQuery.EJS.Helpers.prototype.plugin function
Hooks up a jQuery plugin on.
API
ejs.helpers.plugin(name) ->undefined
name {String}
the plugin name
returns {undefined}
jQuery.EJS.Helpers.prototype.view function
Renders a partial view. This is deprecated in favor of $.View().
API
ejs.helpers.view(url, data,helpers) -> undefined
url {}
data {}
helpers {}
returns {undefined}
jQuery.EJS.prototype.render function
Renders an object with view helpers attached to the view.
new EJS({text: "<%= message%>"}).render({
message: "foo"
},{helper: function(){ ... }})
API
ejs.render(object, extraHelpers)-> String
object {Object}
data to be rendered
extraHelpers {optional:Object}
an object with view helpers
returns {String}
returns the result of the string
jQuery.EJS.static.clean function
Escapes the text provided as html if it's a string.
Otherwise, the value is passed to EJS.text(text).
API
$.EJS.clean(text) -> String
text {String|Object|Array|Function}
to escape. Otherwise, the result of jQuery.EJS.textis returned.
returns {String}
the escaped text or likely a $.View data-view-id attribute.
jQuery.EJS.static.options attribute
Sets default options for all views.
$.EJS.options.type = '['
Only one option is currently supported: type.
Type is the left hand magic tag.
jQuery.EJS.static.text function
Used to convert what's in <%= %> magic tags to a string to beinserted in the rendered output.
Typically, it's a string, and the string is just inserted. However, ifit's a function or an object with a hookup method, it can potentially be be ranon the element after it's inserted into the page.
This is a very nice way of adding functionality through the view. Usuallythis is done with jQuery.EJS.Helpers.prototype.pluginbut the following fades in the div element after it has been inserted:
<%= function(el){$(el).fadeIn()}%>
API
$.EJS.text(input) -> String
input {String|Object|Function}
the value in between the write magic tags: <%= %>
returns {String}
returns the content to be added to the rendered output. The content isdifferent depending on the type:
· jQuery.fn.after function
· Source
· Extending theoriginal jQuery().after() to render jQuery.Viewtemplates inserted after each element in the set of matched elements.
· $('#test').after('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.after(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.fn.append function
· Source
· Extending theoriginal jQuery().append() torender jQuery.Viewtemplates inserted at the end of each element in the set of matched elements.
· $('#test').append('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.append(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.fn.before function
· Source
· Extending theoriginal jQuery().before() torender jQuery.Viewtemplates inserted before each element in the set of matched elements.
· $('#test').before('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.before(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.fn.html function
· Source
· Extending theoriginal jQuery().html() to render jQuery.Viewtemplates as the content of each matched element.
· $('#test').html('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.html(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.fn.prepend function
· Source
· Extending theoriginal jQuery().prepend() torender jQuery.Viewtemplates inserted at the beginning of each element in the set of matchedelements.
· $('#test').prepend('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.prepend(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.fn.replaceWith function
· Source
· Extending theoriginal jQuery().replaceWith()to render jQuery.Viewtemplates replacing each element in the set of matched elements.
· $('#test').replaceWith('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.replaceWith(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.fn.text function
· Source
· Extending theoriginal jQuery().text() to render jQuery.Viewtemplates as the content of each matched element. Unlike jQuery.fn.htmljQuery.fn.text also works with XML, escaping the provided string as necessary.
· $('#test').text('path/to/template.ejs', { name : 'javascriptmvc' });
· API
· $.fn.text(content, data)
· content {String|Object|Function}
· A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.
· data {optional:Object}
· The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).
· jQuery.tmpl class
· plugin:jquery/view/tmpl
· Source
· Provides basictemplating with magic tags that look like:
· ${value}
· jQuery.Viewintegrates jQuery.tmpl templates into your build process. You can use ajQuery.tmpl like:
· $('#area').html('//path/to/template.tmpl',{ data });
· For moreinformation on jQuery.tmpl read it's documentation.
· jQuery.View.cache attribute
· Source
· Should the viewsbe cached or reloaded from the server. Defaults to true.
· jQuery.View.ext attribute
· Source
· The default suffixto use if none is provided in the view's url.
This is set to .ejs by default.
· jQuery.View.hookup function
· Source
· Registers a hookupfunction that can be called back after the html is put on the page. Typicallythis is handled by the template engine. Currently only EJS supports thisfunctionality.
· var id = $.View.hookup(function(el){
· //do something with el
· }),
· html = "<div data-view-id='"+id+"'>"
· $('.foo').html(html);
· API
· $.View.hookup(cb, the) -> undefined
· cb {Function}
· a callbackfunction to be called with the element
· the {Number}
· hookup number
· returns {undefined}
jQuery.View.register function
Registers a template engine to be used with view helpers and compression.
Example
$.View.register({
suffix : "tmpl",
plugin : "jquery/view/tmpl",
renderer: function( id, text ) {
return function(data){
returnjQuery.render( text, data );
}
},
script: function( id, text ) {
var tmpl =$.tmpl(text).toString();
return "function(data){return ("+
tmpl+
").call(jQuery, jQuery, data); }";
}
})
Here's what each property does:
API
$.View.register(info) ->undefined
info {Object}
a object of method and properties
that enable template integration:
returns {undefined}
plugin: jquery/view/micro
A very lightweight template engine. Magic tags look like:
Micro is integrated in JavaScriptMVC so you can use itlike:
$(
"#foo").html(
'//app/views/bar.micro',{});
For more information on micro, see John Resig's write up.
Micro(str, data) -> undefined
{String}
template content.
{Object}
render's the template with this content.
{undefined}