15

I have a web page that uses Haml for layouts. "layout.haml" is a separate layout file which is used when rendering any actual Haml page.

layout.haml looks something like:

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

This is of course already in the document's <body> so manipulating things in the header is not directly possible. For instance <title> is changed via @title. A bigger problem is the fact that every page-specific JavaScript needs to be loaded in the body. Moreover, layout.haml already contains JavaScript, so jQuery is usually instantiated multiple times.

Are there any suggestions for a better template structure?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Philip
  • 3,470
  • 7
  • 29
  • 42
  • For a HAML only app, with partials and layouts, you should check this answer: https://stackoverflow.com/questions/6125265/using-layouts-in-haml-files-independently-of-rails – cobi_z Jun 28 '15 at 00:50

2 Answers2

43

This solution is for Ruby on Rails only:

You can use yield(:location) and the content_for(:location) methods. "Using the content_for Method" has 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!
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
tjwallace
  • 5,528
  • 1
  • 26
  • 15
6

I use partials:

!!!
%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')
kfl62
  • 2,434
  • 4
  • 29
  • 40