6

如何使代码正确缩进?

应用程序/视图/布局/shared.html.haml:

= render :partial => "shared/head"
= yield
= render :partial => "shared/footer"

应用程序/视图/共享/_head.html.haml:

!!!XML
!!!1.1
%html{"xml:lang" => "pl", :xmlns => "http://www.w3.org/1999/xhtml"}
  %head
    %title
      some title
  %body
    .container

应用程序/视图/共享/index.html.haml:

%p
  Hello World!

应用程序/视图/共享/_footer.html.haml:

.footer
  Some copyright text

渲染的 HTML 输出:

<!DOCTYPE html> 
<html xml:lang='pl' xmlns='http://www.w3.org/1999/xhtml'> 
  <head> 
    <title> 
      some title
    </title> 
  </head> 
  <body> 
    <div class='container'></div> 
  </body> 
</html> 
<p> 
  Hello World!
</p> 
<div id='footer'> 
 Some copyright text
</div> 
4

2 回答 2

5

您应该使用app/views/layout它和yield实际内容:

例子

更新

app/views/layout/shared.html.haml

!!! 1.1
%html
  = render "shared/head"
  %body
    .container
      = yield
  = render "shared/foot"
于 2010-09-24T21:31:53.747 回答
1

看起来我在这里参加聚会已经很晚了,但也许其他人会遇到这个并且需要处理同样的问题(就像我今晚所做的那样)。

在我的例子中,我有一个更复杂的打开 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'
于 2012-01-15T07:28:12.307 回答