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.

Ex:

get '/' do
  erd :index
end

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

Ex:

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

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:

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

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

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

layout
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
Content-Type the template produces. Default depends on template language.

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

layout_engine
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

layout_options
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!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s