Skip to content

View Controller#render_as

floere edited this page Sep 13, 2010 · 1 revision

Rendering View Model Templates

View models can have their own templates.

Partials

Use render_as template_name, options, or render_the template_name, options.

view_model = view_model_for Some::Model::Class.new
view_model.render_as :example

Renders views/view_models/some/model/class/_example.erb.

Note: Renders a format depending on the request. Calling /index.text will render _example.text.erb.

Templates

Use render_template name, options.

view_model = view_model_for Some::Model::Class.new
view_model.render_template :example

Renders views/view_models/some/model/class/example.erb.

Note: Renders a format depending on the request. Calling /index.text will render example.text.erb.

With explicit format

view_model.render_as :example, :format => :text

Renders the ‘_example.text.erb’ partial in view_models/some/model/class.

Hierarchical Rendering

If the partial or template cannot be found, it will traverse the view model hierarchy upwards to find a suitable template (based on name and format).

If we have the following view model structure:

class ViewModels::Project < ViewModels::Base
class ViewModels::Profile < ViewModels::Project
class ViewModels::Band < ViewModels::Profile

Then calling render_as(:header, :format => :text) on the band view model will try to render the following templates:

1. views/view_models/band/_header.text.erb
2. views/view_models/profile/_header.text.erb
3. views/view_models/project/_header.text.erb

If it can’t find a suitable template, it will raise a TemplateNotFoundError.

Locals

view_model.render_as :example, :format => :text, :locals => { :name => value }

The locals will be passed to the template as usual.

Clone this wiki locally