tenderlove (owner)

Revisions

gist: 201931 Download_button fork
public
Public Clone URL: git://gist.github.com/201931.git
Embed All Files: show embed
handlebar.html #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<h1>{{header}}</h1>
{{#list}}
  <ul>
  {{#item}}
    {{#current}}
      <li><strong>{{name}}</strong></li>
    {{/current}}
    {{#link}}
      <li><a href="{{url}}">{{name}}</a></li>
    {{/link}}
  {{/item}}
  </ul>
{{/list}}
{{#empty}}
  <p>The list is empty.</p>
{{/empty}}
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require 'benchmark'
require 'examples/complex_view'
 
class Handlebar < ComplexView
  def render_sections(template)
    # fail fast
    return template unless template.include?('{{#')
 
    template.gsub(/\{\{\#([^\}]*)\}\}\s*(.+)\{\{\/\1\}\}\s*/m) do |s|
      ret = find($1)
 
      if ret.respond_to? :each
        ret.map do |ctx|
          render($2, ctx)
        end.join
      elsif ret
        render($2)
      else
        ''
      end
    end
  end
end
 
n = 10000
Benchmark.bm(9) do |x|
  x.report('complex') { n.times { ComplexView.to_html } }
  x.report('handlebar') { n.times { Handlebar.to_html } }
end
 
__END__
user system total real
complex 18.760000 0.710000 19.470000 ( 26.253526)
handlebar 6.320000 0.520000 6.840000 ( 12.494350)