我正在基于设备模板创建模块化Rails模板。我有主要的应用程序布局:
application.html.erb
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= content_for?(:title) ? yield(:title) : "Rails Devise" %></title>
<meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Rails Devise" %>">
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<header>
<%= render 'layouts/navigation' %>
</header>
<main role="main">
<%= render 'layouts/messages' %>
<%= yield %>
</main>
<footer>
<% if File.exist?('layouts/footer') %>
<%= render 'layouts/footer' %>
<% end %>
</footer>
</body>
</html>
我有一个页脚模板,如果文件存在(我可能不存在),我想要包括:
_footer.html.erb
<p class="text-muted">
© <%= Time.now.year.to_s %> All rights reserved
</p>
File.exist?当它在那里时,它不会呈现页脚。如果模板文件存在,如何才能包含页脚?
答案 0 :(得分:1)
不要使用rescue
,这可能非常危险。这样更好
<% if File.exists? Rails.root.join('app/views/layouts/footer.html.erb') %>
<%= render 'layouts/footer' %>
<% end %>
答案 1 :(得分:0)
尝试使用rescue nil
末尾的render
。
render nil
不会显示任何内容。
<%= render 'layouts/footer' rescue nil %>
希望它有所帮助,欢呼!
答案 2 :(得分:0)
使用rescue
比Fail.exists?
策略或template_exists?
策略更好的答案。
更好,因为它使用缓存。
<% if lookup_context.template_exists?('layouts/footer') %>
<%= render 'layouts/footer' %>
<% end %>