2010-12-12 72 views
15

我有一個使用Haml佈局的網頁。有一個單獨的佈局文件(layout.haml),用於渲染任何實際的haml頁面。該layout.haml看起來像在Haml中構建佈局模板

-# layout.haml 
!!! XML 
!!! 
%html 
    %head 
    ... 
    %body 
    ... 
    #content= yield 

的問題:這當然是已經在文件的<body>在標題中這樣操作的東西不能直接成爲可能。例如<title>通過@title更改。什麼是更多的問題是,每個頁面特定的Javascript需要加載到正文中。而且layout.haml已經包含了Javascript,所以jQuery通常被多次實例化。

有關更好的模板結構的任何建議?

+0

對於一個只有HAML應用程序,以諧音和佈局,你應該檢查這個答案: https://stackoverflow.com/questions/6125265/using-layouts-in-haml-files-independent-of-rails – 2015-06-28 00:50:10

回答

43

該解決方案的Ruby on Rails的只有:

您可以使用yield(:location)content_for(:location)方法,more information

layout.haml

!!! 
%html 
    %head 
    %title= yield(:title) 
    = yield(:head) 
    %body 
    = yield 

view.haml

- content_for(:title, 'My title') 
- content_for(:head) do 
    = javascript_include_tag :foo 

%h1 My view! 
+0

嗨,謝謝,這看起來很優雅,我會盡快試一試 – Philip 2010-12-14 14:56:03

+15

請注意,這是一個Rails特定的解決方案。 – 2011-01-22 09:04:29

6

我用諧音:

!!! 
%html 
    = partial('trst_sys/shared/html-head') 

    %body{:id => "srv",:'data-lang' => current_lang} 
    #main.wrap 
    %header#header 
     = partial('trst_sys/shared/header') 
    %nav#menu 
     = partial('trst_sys/shared/menu') 
    %section#content 
     %article#xhr_content 
     = yield 
     %article#xhr_msg.hidden 
    %section#sidebar 
     = partial('trst_sys/shared/sidebar') 
    %section#main_footer.wrap 
    %footer#footer.wrap 
    = partial('trst_sys/shared/footer') 
+0

謝謝,我一定會很快檢查出來的 – Philip 2010-12-14 14:56:20