Module: Cuba::Haml

Defined in:
lib/cuba/haml.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.setup(app) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/cuba/haml.rb', line 5

def self.setup(app)
  app.settings[:haml] ||= {}
  app.settings[:haml][:views] ||= File.expand_path("views", Dir.pwd)
  app.settings[:haml][:layout_path] ||= app.settings[:haml][:views]
  app.settings[:haml][:layout] ||= "layout"
  app.settings[:haml][:options] ||= {
    default_encoding: Encoding.default_external
  }
end

Instance Method Details

#haml(template, locals = {}) ⇒ Object

Use default layout



16
17
18
19
20
# File 'lib/cuba/haml.rb', line 16

def haml(template, locals = {})
  res.write render(layout_path,
            { content: partial(template, locals) }.merge(locals),
            settings[:haml][:options])
end

#layout_path(layout = ) ⇒ Object



40
41
42
43
44
45
# File 'lib/cuba/haml.rb', line 40

def layout_path(layout = settings[:haml][:layout])
  "%s/%s.haml" % [
    settings[:haml][:layout_path],
    layout
  ]
end

#partial(template, locals = {}) ⇒ Object

Skip layout, only renders the template



29
30
31
# File 'lib/cuba/haml.rb', line 29

def partial(template, locals = {})
  render(template_path(template), locals, settings[:haml][:options])
end

#render(template, locals = {}, options = {}, &block) ⇒ Object

Render any type of template file supported by Tilt.

Examples:


# Renders home, and is assumed to be HAML.
render("home")

# Renders with some local variables
render("home", site_name: "My Site")

# Renders with HAML options
render("home", {}, ugly: true, format: :html5)

# Renders in layout
render("layout.haml") { render("home.haml") }


63
64
65
66
67
# File 'lib/cuba/haml.rb', line 63

def render(template, locals = {}, options = {}, &block)
  template = File.read(template)
  ::Haml::Engine.new(template, options.merge(outvar: '@_output'))
                .render(self, locals, &block)
end

#template_path(template) ⇒ Object



33
34
35
36
37
38
# File 'lib/cuba/haml.rb', line 33

def template_path(template)
  "%s/%s.haml" % [
    settings[:haml][:views],
    template
  ]
end

#view(template, layout_file, locals = {}) ⇒ Object

Use specific layout file nested into :layout_path



23
24
25
26
# File 'lib/cuba/haml.rb', line 23

def view(template, layout_file, locals = {})
  res.write render(layout_path(layout_file),
                    { content: partial(template, locals) }.merge(locals))
end