看起来我来这里的聚会已经很晚了,但是也许其他人会遇到这个问题,需要处理同样的问题(就像我今天晚上做的那样)。
在我的例子中,我有一个更复杂的设置来打开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标记从\u head partial中撕下(将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 engine's #def_method
,使布局看起来像这样:
- # /app/views/layout/application.html.haml
= render_html_tag do
= render 'layouts/shared/head'
%body
= yield
= render 'layouts/shared/footer'