Working with Sinatra – Part 2

In the last post I showed how to install Sinatra and how to write a simple code. In these post I’m going to cover Views. View is the V of MVC pattern.

First of all you need to create a folder called views

mkdir views

In this folder you’ll put all your views files .erb or .haml.

To render a view you need to define the format of the view (.erb or .haml) and the name of your view.


get '/' do
  erd :index

This code will render a view called index in the views folder.

Obs: You need to create a view called index.rb in your views folder.

You can also define a template in your views folder and use it in some of your views


get '/' do
  erb :index , layout: :post

This code will render the view index with the post layout (views/post.rb)

There are  many availble options in the options hash.

Here all of them:

List of locals passed to the document. Handy with partials. Example: erb "<%= foo %>", :locals => {:foo => "bar"}

encoding to use if uncertain. Defaults to settings.default_encoding.

Views folder to load templates from. Defaults to settings.views.

Whether to use a layout 
(true or f   alse). If it's a Symbol, specifies what template to use. Example: erb :index, :layout => !request.xhr?

Content-Type the template produces. Default depends on template language.

Scope to render template under. Defaults to the application instance. If you change this, instance variables and helper methods will not be available.

Template engine to use for rendering the layout. Useful for languages that do not support layouts otherwise. Defaults to the engine used for the template. Example: set :rdoc, :layout_engine => :erb

Special options only used for rendering the layout. Example: set :rdoc, :layout_options => { :views => 'views/layouts' }

In the third part of this post we will start coding a simple blog application.

See ya!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s