2010-09-24 58 views
6

如何正確地使代碼縮進?Haml在佈局中呈現多個部分

應用/視圖/佈局/ 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 

應用/視圖/共享/索引。 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> 
+0

非常好的闡述的問題。 – look 2012-06-20 23:00:30

回答

5

您應該使用app/views/layout對於和yield實際內容:

Example

更新

app/views/layout/shared.html.haml

!!! 1.1 
%html 
    = render "shared/head" 
    %body 
    .container 
     = yield 
    = render "shared/foot" 
+0

當我想在多個佈局上使用相同的標題部分時,我必須在所有佈局上重複它...不是非常乾燥,也不是「Ruby方式」 – astropanic 2010-09-24 21:36:45

+0

佈局正好適合您的問題,如果您有更多佈局相同subcontent渲染那些來自公共場所的部分 – 2010-09-24 21:37:43

+0

我已經在上面放置了一個示例,包含頁眉和頁腳的簡單佈局,但正如您所看到的,它不起作用 – astropanic 2010-09-24 21:51:08

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局部的(離開頭標籤存在),並創建了下面的幫助來處理這個問題:

# /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' 
+0

我沒有嘗試過。似乎有點複雜的簡單縮進。但無論如何我都會贊成。 – look 2012-06-20 23:12:22

+0

我不認爲這是一個好的解決方案。上面的共享模板是一個更好的方法。 – Dylan 2012-08-14 05:39:59