没有Rails的Ruby中的部分HAML模板 [英] Partial HAML templating in Ruby without Rails
问题描述
对于我的很小的项目,我真的不需要Rails的开销,所以我试图仅使用简单的Ruby和HAML来实现这一目标.
I really don’t need the overhead of Rails for my very small project, so I’m trying to achieve this just using just plain Ruby and HAML.
我想在我的HAML模板中包含另一个HAML文件.但是我还没有找到一种很好的方法,或者真的有用的方法.
I want to include another HAML file inside my HAML template. But I haven’t found a good—or really usable—way of doing this.
例如,我有以下两个HAML文件:
For example, I have these two HAML files:
documents.haml
documents.haml
%html
%body
= include(menu.haml) body
%article …
menu.haml
menu.haml
%ul
%li
%a whatever …
包含显然不是走这条路的方法.但这在描述本示例中要实现的目标方面做得很好.
Include is obviously not the way to go here. But it does a nice job describing what I’m trying to achieve in this example.
推荐答案
我之前已经这样做过,仅适用于速成模板制作人.最简单的方法是只在父对象中呈现HAML:
I've done this before, just for a quick-and-dirty template producer. The easiest way is to just render the HAML inside the parent object:
%p some haml that's interesting
= Haml::Engine.new('%p this is a test').render
%p some more template
您很可能希望构建一些方法来简化此过程-几个辅助方法.也许您编写了一个名为render_file的文件,它以文件名作为参数.该方法可能类似于:
You'll more than likely want to build some methods to make this easier--a couple of helper methods. Maybe you write one called render_file that takes a filename as an argument. That method might look something like:
def render_file(filename)
contents = File.read(filename)
Haml::Engine.new(contents).render
end
然后,您的模板将更像:
Then, your template would look more like:
%p some template
= render_file('some_filename.haml')
%p more template
注意,您可能需要将self传递给原始的Haml :: Engine渲染,以便它知道如何找到您的render_file方法.
Note, you will probably need to pass self to the original Haml::Engine render so that it knows how to find your render_file method.
这篇关于没有Rails的Ruby中的部分HAML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!