haml入门

来源:互联网 发布:手机淘宝模拟器电脑版 编辑:程序博客网 时间:2024/05/21 10:54

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使用缩进来表示层级关系

1 0