Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure a layout template in Haml

Tags:

ruby

haml

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?

like image 986
Philip Avatar asked Dec 12 '10 13:12

Philip


People also ask

How do you write Haml in HTML?

In Haml, we write a tag by using the percent sign and then the name of the tag. This works for %strong , %div , %body , %html ; any tag you want. Then, after the name of the tag is = , which tells Haml to evaluate Ruby code to the right and then print out the return value as the contents of the tag.

What is a .Haml file?

Haml (HTML Abstraction Markup Language) is a templating system that is designed to avoid writing inline code in a web document and make the HTML cleaner. Haml gives the flexibility to have some dynamic content in HTML.

What is Haml in CSS?

Haml is a markup language that's used to cleanly and simply describe the HTML of any web document, without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ERB, and ASP.


2 Answers

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!
like image 182
tjwallace Avatar answered Sep 29 '22 03:09

tjwallace


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')
like image 36
kfl62 Avatar answered Sep 29 '22 02:09

kfl62