嵌入式 Ruby

在 Rails 视图中添加 Ruby 代码的最流行的方法是使用嵌入 Ruby (ERB)。 嵌入 Ruby 的文件具有.html.erb 扩展,这些文件可以有任何数量的常规 HTML 标记。

以下是基本语法:

1<ul>
2  <% @todo_items.each do |todo| %>
3    <li><%= todo.name %> : <%= todo.priority %></li>
4  <% end %>
5</ul>

这将输出HTML,看起来像这样:

1<ul>
2    <li>Buy milk : Normal</li>
3    <li>Mow land : Urgent</li>
4    <li>Throw a ball : Normal</li>
5    <li>Learn Ruby : Extremely Urgent</li>
6</ul>

注意使用 <% with %> 或 <%= with %>. 这些标签用于包装 Ruby 代码. 将执行 <% 之后的代码,但不会产生任何输出。

以下是ERB中的评论,这些都不会出现在HTML中,甚至不是作为HTML评论:

1<%# Wild Things %>
Published At
Categories with 技术
Tagged with
comments powered by Disqus