Module: Mustache::Sinatra::Helpers

Defined in:
lib/mustache/sinatra.rb

Instance Method Summary collapse

Instance Method Details

#mustache(template, options = {}, locals = {}) ⇒ Object

Call this in your Sinatra routes.



45
46
47
# File 'lib/mustache/sinatra.rb', line 45

def mustache(template, options={}, locals={})
  render :mustache, template, options, locals
end

#render_mustache(template, data, opts, locals, &block) ⇒ Object

This is called by Sinatra’s ‘render` with the proper paths and, potentially, a block containing a sub-view



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/mustache/sinatra.rb', line 51

def render_mustache(template, data, opts, locals, &block)
  # If you have Hurl::App::Views, namespace should be set to Hurl::App.
  Mustache.view_namespace = options.namespace

  # This is probably the same as options.views, but we'll set it anyway.
  # It's used to tell Mustache where to look for view classes.
  Mustache.view_path = options.mustaches

  # Grab the class!
  klass = Mustache.view_class(template)

  # Only cache the data if this isn't the generic base class.
  klass.template = data unless klass == Mustache

  # Confusingly Sinatra's `views` setting tells Mustache where the
  # templates are found. It's fine, blame Chris.
  if klass.template_path != options.views
    klass.template_path = options.views
  end

  # Create a new instance for playing with
  instance = klass.new

  # Copy instance variables set in Sinatra to the view
  instance_variables.each do |name|
    instance.instance_variable_set(name, instance_variable_get(name))
  end

  # Locals get added to the view's context
  locals.each do |local, value|
    instance[local] = value
  end

  # If we're paseed a block it's a subview. Sticking it in yield
  # lets us use {{yield}} in layout.html to render the actual page.
  instance[:yield] = block.call if block

  instance.template = data unless instance.compiled?
  instance.to_html
end