1.什么是Haml
Haml是HTML abstraction markup language,遵循的原则是标记应该是美的。Haml能够加速和简化模版,长处是简洁、可读、高效。
2.erbm模板和haml模板对照
.erb模板代码:
<section class=”container”><h1><%= post.title %></h1><h2><%= post.subtitle %></h2><div class=”content”><%= post.content %></div>
</section> 相同的代码使用haml:
%section.container
%h1= post.title
%h2= post.subtitle.content= post.content 3.安装haml
haml是一个命令行工具。gem安装明令:
gem install haml 安装最新版本号:
gem install haml --pre 在rails项目中更新Gemfile,加入haml依赖:
gem 'haml' 4.erb转haml
haml是erb的一个替代品,app/views下的.erb文件都能够直接改动后缀名更改为haml模板:
app/views/account/login.html.erb → app/views/account/login.html.haml 5.使用haml
5.1 erb代码转haml代码
ERB:
<strong><%= item.title %></strong> Haml:
%strong= item.title 在haml中通过%加标签名的方式表示一个html标签。比方%strong, %div, %body, %html; 标签名后跟=,=告诉haml去计算ruby代码。返回值作为标签的内容。
Haml的会自己主动检測返回值的换行符而且格式化标签。
5.2给标签加入属性:
HTML:
<strong class="code" id="message">Hello, World!</strong> HAML:
%strong{:class => "code", :id => "message"} Hello, World! 5.3简化Div
Html:
<div class='content'>Hello, World!</div> Haml:
.content Hello, World! 5.5 演示样例一
ERB:
<div class='item' id='item<%= item.id %>'><%= item.body %>
</div> HAML:
.item{:id =>"item#{item.id}"} = item.body 5.2 演示样例2
ERB:
<div id='content'><div class='left column'><h2>Welcome to our site!</h2><p><%= print_information %></p></div><div class="right column"><%= render :partial => "sidebar" %></div>
</div> HAML:
#content.left column
%h2 Welcome to our site!
%p = print_information.right column=render :partial => "sidebar" Haml使用缩进来表示层级关系