Structuring of layout template in Haml

2019-03-08 21:20发布

问题:

I have a web page that uses Haml for layouts. There is a separate layout file (layout.haml) which is used when rendering any actual haml page. The layout.haml looks something like

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

The problem: 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. What is something more of a problem is the fact that every page specific Javascript needs to be loaded in the body. Moreover the layout.haml already contains Javascript, so jQuery is usually instantiated multiple times.

Any suggestions for a better template structure?

回答1:

This solution is for Ruby on Rails only:

You can use yield(:location) and the content_for(:location) methods, 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!


回答2:

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')


标签: ruby haml