如何在html.erb文件中使用条件渲染不同的div

时间:2018-08-19 19:36:11

标签: ruby-on-rails ruby view

如果URL包含某些字符串,我试图在.html.erb文件中呈现不同的div:

<% if request.path_info.include?('abc') %>
  <div>ABC</div>
<% elsif request.path_info.include?('xyz')  %>
  <div>XYZ</div>
<% end %>

我找到了以下代码。我尝试了该解决方案,但仍然无法正常工作。任何帮助将不胜感激!

If URL contains string?

The error that is giving me as is follows:

Showing /Users/etc/...../something.html.erb where line #28 raised:

undefined local variable or method `request' for #<#
<Class:>:>
Did you mean?  require
Extracted source (around line #14):
12
13
14
15
16
17

      </div>

      <% if request.path_info.include?('abc') %>
        <div>ABC</div>
      <% elsif request.path_info.include?('xyz')  %>
        <div>XYZ</div>

Rails.root: /Users/etc/....something

1 个答案:

答案 0 :(得分:0)

在调用something.html.erb的控制器方法中,您需要使request为对象。我们需要查看您的控制器代码,但是请尝试以下操作:

def something
  @request = request
end

您可以从那里在erb中访问它,例如:

<% if @request.path_info.include?('abc') %>