简体   繁体   English

Ruby On Rails-基于控制器和操作的HTML条件

[英]Ruby On Rails - HTML Conditional Based On Controller and Action

I have a syntax issue I'm trying to sort out. 我正在尝试解决语法问题。 I'm just trying to check if a controller/action is loaded, and if so do something, and if not do something else, seems simple. 我只是在尝试检查是否加载了控制器/动作,如果这样做,则执行某些操作,如果未执行其他操作,则看起来很简单。 This gives me an error: 这给我一个错误:

<% if (:controller => 'home', :action => 'index') do %>
    <div class="header">
<% else %>
    <div class="header-2">
<% end %>  

Can someone assist me with the syntax issue here? 有人可以在这里帮助我解决语法问题吗? Thank you! 谢谢!

You have to modify the if clause like this: 您必须像这样修改if子句:

<% if controller_name == 'home' && action_name == 'index' %>

Additionally, if have to call this more than once, I'd suggest you define a helper. 此外,如果必须多次调用此函数,建议您定义一个帮助器。

application_helper.rb application_helper.rb

def home_index?
  controller_name == 'home' && action_name == 'index'
end

This way your code will be a lot more readable: 这样,您的代码将更具可读性:

some_view.html.erb some_view.html.erb

<div class='<%= home_index? ? "foo" : "bar" %>'>

You can use a Rails provided helper to check those kind of things (current controller/action, parameters, ...): current_page? 您可以使用Rails提供的帮助程序来检查那些事情(当前控制器/操作,参数等): current_page?

<% if current_page?(controller: 'home', action: 'index') %>
  <div class="header">
<% else %>
  <div class="header-2">
<% end %> 

Documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F 文档: http : //api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F

Using this helper you can also check for specific parameters: 使用此帮助程序,您还可以检查特定的参数:

 current_page?(controller: 'home', action: 'index', page: '2')

In the view, you'll need to check for controller_name and action_name . 在视图中,您需要检查controller_nameaction_name Try this 尝试这个

<% if controller_name == 'home' && action_name == 'index' %>
    <div class="header">
<% else %>
    <div class="header-2">
<% end %> 

Try this in ur view , it will works 在您的视图中尝试一下,它将起作用

<% if (controller_name == 'applications' && action_name == 'index') %>
    <div class="header">
<%else%>
    <div class="header-2">
<%end%>

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

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