Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra Locals vs. Instance Variables

Tags:

ruby

sinatra

What exactly are Sinatra’s locals, and is there any difference between using them in templates as opposed to instance variables? Here’s what I mean by locals:

erb :template, :locals => {:variable => 'value'}

Edit:

In terms of implementation, what are the differences between instance and local variables, and are there any benefits to using one over the other?

like image 615
Cesar Figueroa Avatar asked Jun 10 '13 07:06

Cesar Figueroa


1 Answers

From Sinatra's intro:

Templates are evaluated within the same context as route handlers. Instance variables set in route handlers are directly accessible by templates:

get '/:id' do
  @foo = Foo.find(params[:id])
  haml '%h1= @foo.name'
end

Or, specify an explicit Hash of local variables:

get '/:id' do
  foo = Foo.find(params[:id])
  haml '%h1= bar.name', :locals => { :bar => foo }
end

This is typically used when rendering templates as partials from within other templates.

And for some templates there is (for Radius in this case):

Since you cannot call Ruby methods directly from a Radius template, you almost always want to pass locals to it.

like image 59
Yevgeniy Anfilofyev Avatar answered Oct 29 '22 17:10

Yevgeniy Anfilofyev