简体   繁体   中英

Rails: how do I use javascript conditional on controller/action

是否有一种可接受的方式在应用程序布局中生成javascript,具体取决于控制器/操作是什么?

content_for is the right way to go about here. Based on the current action you could include javascripts required for the particular view. Also however it should be only in the head as loading javascripts in the middle of the page is considered to be obtrusive and hence have a content for in the head of the page. like

<head> <%= yield :dynamic_javascripts %> </head>

and

<% content_for :dynamic_javascripts do %>
  <%= javascript_include_tag "javascript.js" %>
<%end%>

In your application layout you need a "yield" like this:

<html>
  <head>
    <%= yield :head %>
  </head>
  <body>
  </body>
</html>

Then in your controller views you can specify the specific javascript files for that view using:

<% content_for :head do %>
  <%= javascript_include_tag "my_javascript_file.js" %>
<% end %>

The content_for method allows you to insert content into a named yield block in your layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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