【问题标题】:How to render different divs using conditional in a html.erb file如何在 html.erb 文件中使用条件渲染不同的 div
【发布时间】:2018-08-20 23:57:52
【问题描述】:

如果 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

【问题讨论】:

  • 这里有什么问题?
  • @ArupRakshit - 我更新了描述以包含上述错误。谢谢!
  • 你在使用 Rails?
  • 是的,我想是的。
  • 你能从日志中添加完整的错误堆栈吗?我没有看到任何错误代码。

标签: ruby-on-rails ruby view


【解决方案1】:

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

def something
  @request = request
end

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多