前段时间听说rails的模板系统不如django好用,其实rails也有一个比较简洁且好用的模板系统Malline http://www.malline.org/ 。Malline 是专门为Rails框架而设计的模板系统,它从模板系统 Makeaby 获取的灵感,Malline不是嵌入式模板系统,也不是新的语言模板系统,而是使用纯Ruby语言编写模板代码。接触伊始就觉得这个模版真的很棒,下面是根据它的doc做的一个step by step过程。
首先把Malline作为插件进行安装:
ruby script/plugin install http://svn.malline.org/stable/malline
最后在 config/environment.rb中加入 require 'malline/rails' , 这就算安装完毕了。
根据doc测试了2个例子,注意直接把.rhtml文件换为.mn文件即可,rails会直接渲染.mn文件,首先是Malline大大简化了html标签的写法,而且支持嵌套,比如:
div do
span 'text'
div 'foo' do
span 'bar', :style => 'color: red'
end
end
编译成:
<div>
<span>text</span>
<div>
foo<span style="color: red">bar</span>
</div>
</div>
你可以像erb模板那样向block里面输入一个变量,并在以后使用它,比如:
@foo = capture do
div do
img :src => '/images/image.png', :alt => 'nice image'
br
span.caption 'Taken at the location of the event'
end
end
编译成:
<div>
<img src="/images/image.png" alt="nice image"/><br/>
<span class="caption">Taken at the location of the event</span>
</div>
以上是我试验的两个例子,更多可以参见 http://www.malline.org/features ,绝对让你爽个够,而且在下载下来的插件里面包含了大量的测试例子。另外想说明的是,你可以在一个系统里面混用erb模板和malline模板,甚至可以在malline模板里面引用erb模板,比如你已经有一个_one.rhtml的模板,那么在.mn中加入<%= render :partial => 'one' %>也是可行的。