看起来我在这里参加聚会已经很晚了,但也许其他人会遇到这个并且需要处理同样的问题(就像我今晚所做的那样)。
在我的例子中,我有一个更复杂的打开 HTML 标记的设置,以及几种不同的布局,所以我不想要所有的重复。我的打开 HTML 标记具有不同 IE 版本的条件,最初看起来像这样:
- # /app/views/layouts/shared/_head.html.haml
!!! 5
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie ie9"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
%html{ 'xml:lang' => 'en', lang: 'en', class: 'no-js'}
<!--<![endif]-->
%head
- # and so on...
我在过早终止时遇到了同样的问题</html>
,因此我将 HTML 标记从 _head 部分中剥离(将 head 标记留在那里)并创建了以下帮助程序来处理该问题:
# /app/helpers/application_helper.rb
module ApplicationHelper
def render_html_tag(&block)
markup = capture_haml &block
haml = Haml::Engine.new <<-HAML
!!! 5
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie ie9"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
%html{ 'xml:lang' => 'en', lang: 'en', class: 'no-js'}
<!--<![endif]-->
= markup
HAML
obj = Object.new
haml.def_method(obj, :render, :markup)
obj.render(markup: markup)
end
end
它有点乱,也许可以稍微清理一下,但主要思想是利用haml 引擎的 #def_method,它允许布局看起来像这样:
- # /app/views/layout/application.html.haml
= render_html_tag do
= render 'layouts/shared/head'
%body
= yield
= render 'layouts/shared/footer'