简体   繁体   中英

Sinatra pass variables to erb

There's two ways I can do this.

First is to use :locals => {....} and other is to use @var_name . I am just wondering which one is better/preferred? I couldn't find the answer to this anywhere.

Thanks

I have no experience but probably you write less code using @var_name , but if let's say you have 2 actions which render the same view with different objects let's say one with foo and the other with bar, you probably would want to use locals.

def foos
  foos = Foo.all
  erb :something, locals: {list: foos} 
end

def foos
  bars = Foo.all
  erb :something, locals: {list: bars} 
end

Instead of @vars, wich you have to use the same var_name that does not truly represent what's inside. Like: It's a list of what??

def bars
  @list = Bar.all
  erb :something
end

def foos
  @list = Foo.all
  erb :something 
end

Or maybe you should be good with @vars, because most of the time you reuse a view when you render the same kind of objects like:

def foos
  @foos = Foo.all
  erb :something
end

def bar_foos
  @foos = Foo.where(bar: true)
  erb :something 
end

So you probably just want to use locals when rendering partials wich most of the time are used in different contexts. Like a form when you render for a @new_bar, and and existing @bar. Just an example. Or for example a @current_user or a simple @user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM