Skip to content

Commit a493d1e

Browse files
committed
Add simple partials implementation
Add a `render` method to Haml::Helpers to provide a simple implementation of partials.
1 parent ad22479 commit a493d1e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

lib/haml/partials.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
require 'haml'
2+
3+
module Haml::Helpers
4+
5+
# A simple implementation of partials.
6+
#
7+
# Renders the named Haml file and returns the generated HTML.
8+
#
9+
# If the named file is not found, the suffixes +.haml+ and +.html.haml+ are
10+
# added and looked for, and then the same names but with the prefix +_+. The
11+
# first file found will be used.
12+
#
13+
# +self+ is used as the context, so instance variables can be used in the
14+
# partial and will have the same value as the parent template.
15+
#
16+
# This method makes no effort to cache the generated Ruby code, it simply
17+
# uses +Haml::Engine.new().render+ each time.
18+
#
19+
# @param partial [#to_s] the filename of the partial to render
20+
# @param locals [Hash] a hash of local variables to use in the partial
21+
# @return [String] the HTML generated from the partial
22+
# @raise [StandardError] if the partial file cannot be found
23+
24+
def render(partial, locals = {})
25+
Haml::Engine.new(File.read(find_file_for_partial(partial))).render(self, locals)
26+
end
27+
28+
private
29+
def find_file_for_partial(file)
30+
['', '_'].each do |prefix|
31+
['', '.haml', '.html.haml'].each do |suffix|
32+
candidate = "#{prefix}#{file}#{suffix}"
33+
return candidate if File.exist? candidate
34+
end
35+
end
36+
37+
raise "Partial #{file} not found"
38+
end
39+
40+
end

0 commit comments

Comments
 (0)