Class: Mustache

Inherits:
Object
  • Object
show all
Defined in:
lib/mustache.rb,
lib/mustache/parser.rb,
lib/mustache/context.rb,
lib/mustache/sinatra.rb,
lib/mustache/version.rb,
lib/mustache/template.rb,
lib/mustache/generator.rb

Overview

Mustache is the base class from which your Mustache subclasses should inherit (though it can be used on its own).

The typical Mustache workflow is as follows:

  • Create a Mustache subclass: class Stats < Mustache

  • Create a template: stats.mustache

  • Instantiate an instance: view = Stats.new

  • Render that instance: view.render

You can skip the instantiation by calling ‘Stats.render` directly.

While Mustache will do its best to load and render a template for you, this process is completely customizable using a few options.

All settings can be overriden at the class level.

For example, going with the above example, we can use ‘Stats.template_path = “/usr/local/templates”` to specify the path Mustache uses to find templates.

Here are the available options:

  • template_path

The ‘template_path` setting determines the path Mustache uses when looking for a template. By default it is “.” Setting it to /usr/local/templates, for example, means (given all other settings are default) a Mustache subclass `Stats` will try to load /usr/local/templates/stats.mustache

  • template_extension

The ‘template_extension` is the extension Mustache uses when looking for template files. By default it is “mustache”

  • template_file

You can tell Mustache exactly which template to us with this setting. It can be a relative or absolute path.

  • template

Sometimes you want Mustache to render a string, not a file. In those cases you may set the ‘template` setting. For example:

>> Mustache.render("Hello {{planet}}", :planet => "World!")
=> "Hello World!"

The ‘template` setting is also available on instances.

view = Mustache.new
view.template = "Hi, {{person}}!"
view[:person] = 'Mom'
view.render # => Hi, mom!
  • view_namespace

To make life easy on those developing Mustache plugins for web frameworks or other libraries, Mustache will attempt to load view classes (i.e. Mustache subclasses) using the ‘view_class` class method. The `view_namespace` tells Mustache under which constant view classes live. By default it is `Object`.

  • view_path

Similar to ‘template_path`, the `view_path` option tells Mustache where to look for files containing view classes when using the `view_class` method.

Direct Known Subclasses

Rack::Bug::MustachePanel::View

Defined Under Namespace

Modules: Sinatra Classes: Context, ContextMiss, Generator, Parser, Template

Constant Summary collapse

Version =
VERSION = '0.98.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#raise_on_context_miss=(value) ⇒ Object (writeonly)

Sets the attribute raise_on_context_miss

Parameters:

  • value

    the value to set the attribute raise_on_context_miss to.



335
336
337
# File 'lib/mustache.rb', line 335

def raise_on_context_miss=(value)
  @raise_on_context_miss = value
end

Class Method Details

.classify(underscored) ⇒ Object

template_partial => TemplatePartial



267
268
269
270
271
# File 'lib/mustache.rb', line 267

def self.classify(underscored)
  underscored.split(/[-_]/).map do |part|
    part[0] = part[0].chr.upcase; part
  end.join
end

.compiled?Boolean

Has this template already been compiled? Compilation is somewhat expensive so it may be useful to check this before attempting it.

Returns:

  • (Boolean)


257
258
259
# File 'lib/mustache.rb', line 257

def self.compiled?
  @template.is_a? Template
end

.inheritable_config_for(attr_name, default) ⇒ Object

Return the value of the configuration setting on the superclass, or return the default.

attr_name - Symbol name of the attribute. It should match the instance variable. default - Default value to use if the superclass does not respond.

Returns the inherited or default configuration setting.



301
302
303
# File 'lib/mustache.rb', line 301

def self.inheritable_config_for(attr_name, default)
  superclass.respond_to?(attr_name) ? superclass.send(attr_name) : default
end

.partial(name) ⇒ Object

Given a name, attempts to read a file and return the contents as a string. The file is not rendered, so it might contain {mustaches}.

Call ‘render` if you need to process it.



108
109
110
# File 'lib/mustache.rb', line 108

def self.partial(name)
  File.read("#{template_path}/#{name}.#{template_extension}")
end

.pathObject

Alias for ‘template_path`



131
132
133
# File 'lib/mustache.rb', line 131

def self.path
  template_path
end

.path=(path) ⇒ Object

Alias for ‘template_path`



136
137
138
# File 'lib/mustache.rb', line 136

def self.path=(path)
  self.template_path = path
end

.raise_on_context_miss=(boolean) ⇒ Object



251
252
253
# File 'lib/mustache.rb', line 251

def self.raise_on_context_miss=(boolean)
  @raise_on_context_miss = boolean
end

.raise_on_context_miss?Boolean

Should an exception be raised when we cannot find a corresponding method or key in the current context? By default this is false to emulate ctemplate’s behavior, but it may be useful to enable when debugging or developing.

If set to true and there is a context miss, ‘Mustache::ContextMiss` will be raised.

Returns:

  • (Boolean)


247
248
249
# File 'lib/mustache.rb', line 247

def self.raise_on_context_miss?
  @raise_on_context_miss
end

.render(*args) ⇒ Object

Instantiates an instance of this class and calls ‘render` with the passed args.

Returns a rendered String version of a template



77
78
79
# File 'lib/mustache.rb', line 77

def self.render(*args)
  new.render(*args)
end

.render_file(name, context = {}) ⇒ Object

Given a file name and an optional context, attempts to load and render the file as a template.



93
94
95
# File 'lib/mustache.rb', line 93

def self.render_file(name, context = {})
  render(partial(name), context)
end

.templateObject

The template is the actual string Mustache uses as its template. There is a bit of magic here: what we get back is actually a Mustache::Template object here, but you can still safely use ‘template=` with a string.



176
177
178
# File 'lib/mustache.rb', line 176

def self.template
  @template ||= templateify(File.read(template_file))
end

.template=(template) ⇒ Object



180
181
182
# File 'lib/mustache.rb', line 180

def self.template=(template)
  @template = templateify(template)
end

.template_extensionObject

A Mustache template’s default extension is ‘mustache’



141
142
143
# File 'lib/mustache.rb', line 141

def self.template_extension
  @template_extension ||= inheritable_config_for :template_extension, 'mustache'
end

.template_extension=(template_extension) ⇒ Object



145
146
147
148
# File 'lib/mustache.rb', line 145

def self.template_extension=(template_extension)
  @template_extension = template_extension
  @template = nil
end

.template_fileObject

The template file is the absolute path of the file Mustache will use as its template. By default it’s ./class_name.mustache



163
164
165
# File 'lib/mustache.rb', line 163

def self.template_file
  @template_file || "#{path}/#{template_name}.#{template_extension}"
end

.template_file=(template_file) ⇒ Object



167
168
169
170
# File 'lib/mustache.rb', line 167

def self.template_file=(template_file)
  @template_file = template_file
  @template = nil
end

.template_nameObject

The template name is the Mustache template file without any extension or other information. Defaults to ‘class_name`.



152
153
154
# File 'lib/mustache.rb', line 152

def self.template_name
  @template_name || underscore
end

.template_name=(template_name) ⇒ Object



156
157
158
159
# File 'lib/mustache.rb', line 156

def self.template_name=(template_name)
  @template_name = template_name
  @template = nil
end

.template_pathObject

The template path informs your Mustache subclass where to look for its corresponding template. By default it’s the current directory (“.”)



121
122
123
# File 'lib/mustache.rb', line 121

def self.template_path
  @template_path ||= inheritable_config_for :template_path, '.'
end

.template_path=(path) ⇒ Object



125
126
127
128
# File 'lib/mustache.rb', line 125

def self.template_path=(path)
  @template_path = File.expand_path(path)
  @template = nil
end

.templateify(obj) ⇒ Object

Turns a string into a Mustache::Template. If passed a Template, returns it.



286
287
288
289
290
291
292
# File 'lib/mustache.rb', line 286

def self.templateify(obj)
  if obj.is_a?(Template)
    obj
  else
    Template.new(obj.to_s)
  end
end

.to_html(*args) ⇒ Object

Alias for ‘render`



82
83
84
# File 'lib/mustache.rb', line 82

def self.to_html(*args)
  render(*args)
end

.to_text(*args) ⇒ Object

Alias for ‘render`



87
88
89
# File 'lib/mustache.rb', line 87

def self.to_text(*args)
  render(*args)
end

.underscore(classified = name) ⇒ Object

TemplatePartial => template_partial Takes a string but defaults to using the current class’ name.



275
276
277
278
279
280
281
282
# File 'lib/mustache.rb', line 275

def self.underscore(classified = name)
  classified = name if classified.to_s.empty?
  classified = superclass.name if classified.to_s.empty?

  string = classified.dup.split('::').last
  string[0] = string[0].chr.downcase
  string.gsub(/[A-Z]/) { |s| "_#{s.downcase}"}
end

.view_class(name) ⇒ Object

When given a symbol or string representing a class, will try to produce an appropriate view class. e.g.

Mustache.view_namespace = Hurl::Views
Mustache.view_class(:Partial) # => Hurl::Views::Partial


210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/mustache.rb', line 210

def self.view_class(name)
  if name != classify(name.to_s)
    name = classify(name.to_s)
  end

  # Emptiness begets emptiness.
  if name.to_s == ''
    return Mustache
  end

  file_name = underscore(name)
  namespace = view_namespace

  if namespace.const_defined?(:Views) && namespace::Views.const_defined?(name)
    namespace::Views.const_get(name)
  elsif namespace.const_defined?(name)
    namespace.const_get(name)
  elsif File.exists?(file = "#{view_path}/#{file_name}.rb")
    require "#{file}".chomp('.rb')
    if namespace.const_defined?(:Views)
      namespace::Views.const_get(name)
    else
      namespace.const_get(name)
    end
  else
    Mustache
  end
rescue NameError
  Mustache
end

.view_namespaceObject

The constant under which Mustache will look for views. By default it’s ‘Object`, but it might be nice to set it to something like `Hurl::Views` if your app’s main namespace is ‘Hurl`.



187
188
189
# File 'lib/mustache.rb', line 187

def self.view_namespace
  @view_namespace ||= inheritable_config_for(:view_namespace, Object)
end

.view_namespace=(namespace) ⇒ Object



191
192
193
# File 'lib/mustache.rb', line 191

def self.view_namespace=(namespace)
  @view_namespace = namespace
end

.view_pathObject

Mustache searches the view path for .rb files to require when asked to find a view class. Defaults to “.”



197
198
199
# File 'lib/mustache.rb', line 197

def self.view_path
  @view_path ||= inheritable_config_for(:view_path, '.')
end

.view_path=(path) ⇒ Object



201
202
203
# File 'lib/mustache.rb', line 201

def self.view_path=(path)
  @view_path = path
end

Instance Method Details

#[](key) ⇒ Object

Context accessors.

view = Mustache.new view = “Jon” view.template = “Hi, {name}!” view.render # => “Hi, Jon!”



350
351
352
# File 'lib/mustache.rb', line 350

def [](key)
  context[key.to_sym]
end

#[]=(key, value) ⇒ Object



354
355
356
# File 'lib/mustache.rb', line 354

def []=(key, value)
  context[key.to_sym] = value
end

#compiled?Boolean

Has this instance or its class already compiled a template?

Returns:

  • (Boolean)


262
263
264
# File 'lib/mustache.rb', line 262

def compiled?
  (@template && @template.is_a?(Template)) || self.class.compiled?
end

#contextObject

A helper method which gives access to the context at a given time. Kind of a hack for now, but useful when you’re in an iterating section and want access to the hash currently being iterated over.



340
341
342
# File 'lib/mustache.rb', line 340

def context
  @context ||= Context.new(self)
end

#escapeHTML(str) ⇒ Object

Override this to provide custom escaping.

class PersonView < Mustache

def escapeHTML(str)
  my_html_escape_method(str)
end

end

Returns a String



327
328
329
# File 'lib/mustache.rb', line 327

def escapeHTML(str)
  CGI.escapeHTML(str)
end

#partial(name) ⇒ Object

Override this in your subclass if you want to do fun things like reading templates from a database. It will be rendered by the context, so all you need to do is return a string.



115
116
117
# File 'lib/mustache.rb', line 115

def partial(name)
  self.class.partial(name)
end

#raise_on_context_miss?Boolean

Instance level version of ‘Mustache.raise_on_context_miss?`

Returns:

  • (Boolean)


332
333
334
# File 'lib/mustache.rb', line 332

def raise_on_context_miss?
  self.class.raise_on_context_miss? || @raise_on_context_miss
end

#render(data = template, ctx = {}) ⇒ Object Also known as: to_html, to_text

Parses our fancy pants template file and returns normal file with all special {tags} and Mustache.{{#sections}replaced{/sections}.

data - A String template or a Hash context. If a Hash is given,

      we'll try to figure out the template from the class.
ctx - A Hash context if `data` is a String template.

Examples

@view.render("Hi {{thing}}!", :thing => :world)

View.template = "Hi {{thing}}!"
@view = View.new
@view.render(:thing => :world)

Returns a rendered String version of a template



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/mustache.rb', line 374

def render(data = template, ctx = {})
  if data.is_a? Hash
    ctx = data
    tpl = templateify(template)
  elsif data.is_a? Symbol
    old_template_name = self.class.template_name
    self.class.template_name = data
    tpl = templateify(template)
    self.class.template_name = old_template_name
  else
    tpl = templateify(data)
  end

  return tpl.render(context) if ctx == {}

  begin
    context.push(ctx)
    tpl.render(context)
  ensure
    context.pop
  end
end

#render_file(name, context = {}) ⇒ Object

Given a file name and an optional context, attempts to load and render the file as a template.



99
100
101
# File 'lib/mustache.rb', line 99

def render_file(name, context = {})
  self.class.render_file(name, context)
end

#templateObject

The template can be set at the instance level.



310
311
312
# File 'lib/mustache.rb', line 310

def template
  @template ||= self.class.template
end

#template=(template) ⇒ Object



314
315
316
# File 'lib/mustache.rb', line 314

def template=(template)
  @template = templateify(template)
end

#templateify(obj) ⇒ Object



305
306
307
# File 'lib/mustache.rb', line 305

def templateify(obj)
  self.class.templateify(obj)
end