简体   繁体   English

Sinatra将变量传递给erb

[英]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 . 首先是使用:locals => {....} ,其他是使用@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. 我没有经验,但可能你使用@var_name编写更少的代码,但如果让我们说你有2个动作使用不同的对象呈现相同的视图让我们说一个用foo而另一个用bar,你可能会想要使用本地。

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. 而不是@vars,你必须使用相同的var_name,它不能真正代表内部的内容。 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: 或者也许你应该对@vars很好,因为大多数时候你在渲染相同类型的对象时重用一个视图:

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. 就像渲染@new_bar和现有@bar时的表单一样。 Just an example. 只是一个例子。 Or for example a @current_user or a simple @user 或者例如@current_user或简单的@user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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