class Mustache::Context
executed within. All Mustache tags reference keys in the Context.
A Context represents the context which a Mustache template is
def [](name)
def [](name) fetch(name, nil) end
def []=(name, value)
Can be used to add a value to the context in a hash-like way.
def []=(name, value) push(name => value) end
def escapeHTML(str)
Allows customization of how Mustache escapes things.
def escapeHTML(str) mustache_in_stack.escapeHTML(str) end
def fetch(name, default = :__raise)
If no second parameter is passed (or raise_on_context_miss is
second parameter.
stack. You may specify the default return value by passing a
Similar to Hash#fetch, finds a value by `name` in the context's
def fetch(name, default = :__raise) @stack.each do |frame| # Prevent infinite recursion. next if frame == self value = find(frame, name, :__missing) if value != :__missing return value end end if default == :__raise || mustache_in_stack.raise_on_context_miss? raise ContextMiss.new("Can't find #{name} in #{@stack.inspect}") else default end end
def find(obj, key, default = nil)
key is not found.
default - An optional default value, to return if the
key - The key whose value you want.
obj - The object to perform the lookup on.
invokes that method. You get the idea.
If it's an object that responds to the key as a method call,
appropriate. If the object is a hash, does a simple hash lookup.
Finds a key in an object, using whatever method is most
def find(obj, key, default = nil) hash = obj.respond_to?(:has_key?) if hash && obj.has_key?(key) obj[key] elsif hash && obj.has_key?(key.to_s) obj[key.to_s] elsif !hash && obj.respond_to?(key) meth = obj.method(key) if meth.arity == 1 meth.to_proc else meth[] end else default end end
def has_key?(key)
Do we know about a particular key? In other words, will calling
def has_key?(key) !!fetch(key) rescue ContextMiss false end
def initialize(mustache)
def initialize(mustache) @stack = [mustache] end
def mustache_in_stack
Find the first Mustache in the stack. If we're being rendered
def mustache_in_stack @stack.detect { |frame| frame.is_a?(Mustache) } end
def partial(name, indentation = '')
representing your profile page or some other template) responds
If the Mustache view handling the rendering (e.g. the view
`partial` method, which would be this sucker right here.
A {{>partial}} tag translates into a call to the context's
def partial(name, indentation = '') # Look for the first Mustache in the stack. mustache = mustache_in_stack # Indent the partial template by the given indentation. part = mustache.partial(name).to_s.gsub(/^/, indentation) # Call the Mustache's `partial` method and render the result. result = mustache.render(part, self) end
def pop
internal stack.
Removes the most recently added object from the context's
def pop @stack.shift self end
def push(new)
Adds a new object to the context's internal stack.
def push(new) @stack.unshift(new) self end