手把手教你学习ROR-1.Haml

手把手教你学习ROR-1.Haml

1 What is Haml?

Haml是对传统XHTML的生成方式的另一种表现形式。Haml让你撇开臃肿丑陋的模板,将它们以优雅整洁的代码代替。

2 How to get Haml?

Standard Gem

Most people will just want the standard stable Haml gem. To install this:

gem install haml

Pre-Release Gem
To get the latest and greatest Haml goodness, you can install the prerelease gem:
gem install haml --pre

3 How Haml Works?

可以先看一段代码。

传统的div混合erb的代码:
<div id="profile">
<div class="left column">
<div id="date"><%= print_date %></div>
</div>
<div class="right column">
<div id="email"><%= current_user.email %></div>
<div id="bio"><%= h current_user.bio %></div>
</div>
</div>

使用Haml的代码:
#profile
.left.column
#date= print_date
#address= current_user.address
.right.column
#email= current_user.email
#bio= h(current_user.bio)

从上面可以看出:
A Haml使用缩进代替层级关系
B id用"#",class用"."代替,与CSS写法一致
C 混杂使用erb的用法时,使用"="联系,#date= print_date
D 标签用%表示,%h1

4 Advanced in Haml

A 使用Haml,只需更改后缀名
app/views/account/login.html.erb → app/views/account/login.html.haml

B Div+CSS更改为Haml
B.1
HTML
<strong class="code" id="message">Hello, World!</strong>

Haml
%strong{:class => "code", :id => "message"} Hello, World!
%strong.code#message Hello, World!

B.2
HTML
<div class='item' id='item<%= item.id %>'>
<%= item.body %>
</div>

Haml
.item {:id=>"item#{item.id}"}=item.body

C if else的使用
- if condition
= something
- else
= something_else

D -#代表注释

E | 同一句换行时使用

原文地址:https://www.cnblogs.com/SoulSpirit/p/3335401.html