如何在 html.erb 文件中运行多行 Ruby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3099904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I run multiple lines of Ruby in html.erb file
提问by ben
I'm using Ruby on Rails and need to run a block of Ruby code in one of my html.erb files. Do I do it like this:
我正在使用 Ruby on Rails,需要在我的一个 html.erb 文件中运行一段 Ruby 代码。我是不是这样做的:
<% def name %>
<% name = username %>
<%= name %>
or like this:
或者像这样:
<% def name
name = username %>
<%= name %>
Thanks for reading.
谢谢阅读。
采纳答案by shingara
It is unusual to define a method in an ERB file, so I recommend against it.
在 ERB 文件中定义方法是不常见的,所以我建议不要这样做。
If you want to call a block like #each, you can do something like the following:
如果你想调用一个类似 的块#each,你可以执行如下操作:
<% names.each do |name| %>
<%= name %>
<% end %>
Don't forget the <% end %>.
不要忘记<% end %>.
回答by nathanvda
If you need extra functions in your view, you normally declare those inside a helper.
如果您的视图中需要额外的函数,您通常会在 helper 中声明这些函数。
For each controller, if there is a helper it is automatically loaded. For instance, if you have a PeopleController, in the app/helpersfolder, there should be a people_helper.rb, and it should look like this
对于每个控制器,如果有帮助程序,它会自动加载。例如,如果你有一个 PeopleController,在app/helpers文件夹中,应该有一个people_helper.rb,它应该是这样的
module PeopleHelper
def name
#do something
username
end
end
Another, very clean alternative, is to use the Presenterpattern, but i think it is less common (unfortunately).
另一个非常干净的选择是使用Presenter模式,但我认为它不太常见(不幸的是)。
Otherwise, if you do need multiple lines of ruby code inside a erb view, which i try to avoid, i prefer the following style:
否则,如果您确实需要在 erb 视图中使用多行 ruby 代码(我尽量避免这种情况),我更喜欢以下样式:
<%
counter_1 = 0
counter_2 = 1
do_some_more_prep_here
%>
<% @records.each do |rec|%>
<%# do something with the prepped date in each row %>
<% end %>
Also for me code indentation is more important than html indentation, so i will prefer something like
对我来说,代码缩进比 html 缩进更重要,所以我更喜欢类似的东西
<table>
<% @rows.each do |row| %>
<tr>
<td><%= row.item1 %></td>
<% if row.some_test %>
<td><%= row.item2 %></td>
<% end %>
</tr>
<% end %>
</table>
But i am always very interested to hear different opinions in this matter.
但我总是很想听到关于这个问题的不同意见。
回答by x-yuri
I can imagine someone needing it in one particular template (no point in creating a helper) to not duplicate html markup. That is, when resulting html page has a couple of similar blocks of html markup. Though, it can easily be abused (unreadable code).
我可以想象有人在一个特定的模板中需要它(创建助手没有意义)不复制 html 标记。也就是说,当生成的 html 页面有几个类似的 html 标记块时。但是,它很容易被滥用(不可读的代码)。
<% def f1(a, b, c) %>
test: <%= a %>, <%= b %>, <%= c %>
<% end %>
<% f1(1, 2, 3) %>
<% f1(4, 5, 6) %>

