0

我有一个需要包含一些js的部分:view/main/ _address_slider.html.erb

<% content_for :scripts  do %>
<%= javascript_include_tag 'swipeslider/dist/idangerous.swiper.min' %>
<%= javascript_include_tag 'fineuploader' %>
<% end %>
...

我有一个测试页面:view/main/ test_partial_address_slider.html.erb

<% content_for :scripts  do %>
<%= javascript_include_tag 'swipeslider/dist/idangerous.swiper.min' %>
<%= javascript_include_tag 'mycustomplugin' %>
<% end %>
<% render 'address_slider' %>

我有一个特定的测试布局:view/layouts/ test.html.erb

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="description" content="Social Network">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title><%= @meta_title %></title>
<%= yield :meta %>
<%= yield :styles %>
<%= yield :scripts %>
</head>
<body>
<div id="page">
<%= display_flash %>
<%= yield %>
</div>
</body>
</html>

比在我的控制器中:controllers/main_controller

def test_partial_address_slider
render "test_partial_address_slider", layout: "test"
end

渲染的页面包含两次 swipeslider/dist/idangerous.swiper.min 的 js 导入。

<head>
<meta charset="utf-8">
<meta name="description" content="Social Network">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>....</title> 
<script src="/assets/swipeslider/dist/idangerous.swiper.min.js?body=1" type="text/javascript"></script>
<script src="/assets/swipeslider/dist/idangerous.swiper.min.js?body=1" type="text/javascript"></script>
<script src="/assets/fineuploader.js?body=1" type="text/javascript"></script>
<script src="/assets/mycustomplugin.js?body=1" type="text/javascript"></script>
</head>

我可以在布局中的产量之前从 content_for 中删除重复项吗?

4

2 回答 2

0

您可以像这样使用助手:

def yield_something_once
  unless @yielded_something
    @yielded_something = true
    content_for :something
  end
end

或者只是在清除它content_for(:smth, '')之后立即使用。yield :smth

于 2014-11-22T12:34:57.393 回答
0

我找到了一个修复方法,但它看起来很糟糕!

<% s = yield(:scripts)  %>
<%= (((s.split("<script").uniq.collect{|x| x.strip}).reject(&:empty?)).map! { |word| "<script #{word}" }).join("\n").html_safe %>
于 2014-11-22T13:11:40.730 回答