View.Helpers

Related

View.Helpers API, View Overview, View API

Similar to Ruby on Rails View helpers, JavaScriptMVC View.Helper methods are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (*.ejs) is short and sweet, so you can see the structure of the output. Nitty-gritty details are best left to helper methods and partials, where they can be parametrized and used repeatedly.

Examples

link_to('New recipe', '#recipes/new_instance')
--> <a href="#recipes/new_instance">New recipe</a>

img_tag('maid.png')
--> <img src="resources/images/maid.png"/>

text_field_tag('recipe[title]')
--> <textarea id="recipe[instructions]" rows="4" cols="50" name="recipe[instructions]"/>

text_field_tag('recipe[title]')
--> <input id="recipe[title]" type="text" name="recipe[title]" value=""/>

submit_tag('Submit')
--> <input type="submit" value="Submit" name="commit"/>

Define your own

The provided view helpers cover many common cases where you'll need to produce common HTML. In your applications, you'll definitely run into situations where you'll find yourself putting a lot of code into your view. When this happens, you may want to write a view helper to generate this HTML, where it can be better managed and reused.

Example

MVC.View.Helpers.prototype.link_to_recipe = function(recipe){
	return this.link_to(recipe.title,'http://recipes.com/search?'+recipe.name);
};
Define your helper
<%= link_to_recipe(recipe) %>
Use it in your views

Install

View.Helpers is included as part of the View plugin. Simply include the view plugin.

include.plugins('view')