haml入门

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

esc_ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值