Sha256: df406f4bb8bad6886edf40dd0a0fbd535f8b6448c59c877be56dc96e423ebba9

Contents?: true

Size: 1.73 KB

Versions: 1

Compression:

Stored size: 1.73 KB

Contents

require 'sinatra/base'
require 'mustache'

class Mustache
  # Support for Mustache in your Sinatra app.
  #
  #   require 'mustache/sinatra'
  #
  #   class App < Sinatra::Base
  #     helpers Mustache::Sinatra
  #
  #     get '/stats' do
  #       mustache :stats
  #     end
  #   end
  #
  # If a `Views::Stats` class exists in the above example,
  # Mustache will try to instantiate and use it for the rendering.
  #
  # If no `Views::Stats` class exists Mustache will render the template
  # file directly.
  #
  # You can indeed use layouts with this library. Where you'd normally
  # <%= yield %> you instead {{{yield}}} - the body of the subview is
  # set to the `yield` variable and made available to you.
  module Sinatra
    # Call this in your Sinatra routes.
    def mustache(template, options={}, locals={})
      render :mustache, template, options, locals
    end

    # This is called by Sinatra's `render` with the proper paths
    # and, potentially, a block containing a sub-view
    def render_mustache(template, data, options, locals, &block)
      name = Mustache.classify(template.to_s)

      if defined?(Views) && Views.const_defined?(name)
        instance = Views.const_get(name).new
      else
        instance = Mustache.new
      end

      instance_variable_names.each do |name|
        instance.instance_variable_set(name, instance_variable_get(name))
      end

      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
      instance.to_html
    end
  end
end

Sinatra.helpers Mustache::Sinatra

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mustache-0.1.1 lib/mustache/sinatra.rb