如何在Haml中构建布局模板 [英] How to structure a layout template in Haml
问题描述
我有一个使用Haml进行布局的网页. "layout.haml"是一个单独的布局文件,在呈现任何实际的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类似于:
layout.haml looks something like:
-# layout.haml
!!! XML
!!!
%html
%head
...
%body
...
#content= yield
这当然已经在文档的<body>
中,因此无法直接在标头中进行操作.例如,通过@title
更改了<title>
.一个更大的问题是,每个页面特定的JavaScript都需要加载到主体中.而且,layout.haml已经包含JavaScript,因此jQuery通常被实例化多次.
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?
推荐答案
此解决方案仅适用于Ruby on Rails:
This solution is for Ruby on Rails only:
您可以使用yield(:location)
和content_for(:location)
方法. "使用content_for
方法"具有更多内容信息.
You can use yield(:location)
and the content_for(:location)
methods. "Using the content_for
Method" has more information.
layout.haml:
layout.haml:
!!!
%html
%head
%title= yield(:title)
= yield(:head)
%body
= yield
view.haml:
view.haml:
- content_for(:title, 'My title')
- content_for(:head) do
= javascript_include_tag :foo
%h1 My view!
这篇关于如何在Haml中构建布局模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!