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 =
'0.9.1'

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.



293
294
295
# File 'lib/mustache.rb', line 293

def raise_on_context_miss=(value)
  @raise_on_context_miss = value
end

Class Method Details

.classify(underscored) ⇒ Object

template_partial => TemplatePartial



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

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)


239
240
241
# File 'lib/mustache.rb', line 239

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

.pathObject

Alias for ‘template_path`



113
114
115
# File 'lib/mustache.rb', line 113

def self.path
  template_path
end

.path=(path) ⇒ Object

Alias for ‘template_path`



118
119
120
# File 'lib/mustache.rb', line 118

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

.raise_on_context_miss=(boolean) ⇒ Object



233
234
235
# File 'lib/mustache.rb', line 233

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)


229
230
231
# File 'lib/mustache.rb', line 229

def self.raise_on_context_miss?
  @raise_on_context_miss
end

.render(*args) ⇒ Object

Helper method for quickly instantiating and rendering a view.



74
75
76
# File 'lib/mustache.rb', line 74

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.



90
91
92
93
# File 'lib/mustache.rb', line 90

def self.render_file(name, context = {})
  data = File.read("#{template_path}/#{name}.#{template_extension}")
  render(data, 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.



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

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

.template=(template) ⇒ Object



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

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

.template_extensionObject

A Mustache template’s default extension is ‘mustache’



123
124
125
# File 'lib/mustache.rb', line 123

def self.template_extension
  @template_extension ||= 'mustache'
end

.template_extension=(template_extension) ⇒ Object



127
128
129
130
# File 'lib/mustache.rb', line 127

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



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

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

.template_file=(template_file) ⇒ Object



149
150
151
152
# File 'lib/mustache.rb', line 149

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`.



134
135
136
# File 'lib/mustache.rb', line 134

def self.template_name
  @template_name || underscore
end

.template_name=(template_name) ⇒ Object



138
139
140
141
# File 'lib/mustache.rb', line 138

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 (“.”)



103
104
105
# File 'lib/mustache.rb', line 103

def self.template_path
  @template_path ||= '.'
end

.template_path=(path) ⇒ Object



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

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.



268
269
270
271
272
273
274
# File 'lib/mustache.rb', line 268

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`



79
80
81
# File 'lib/mustache.rb', line 79

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

.to_text(*args) ⇒ Object

Alias for ‘render`



84
85
86
# File 'lib/mustache.rb', line 84

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.



257
258
259
260
261
262
263
264
# File 'lib/mustache.rb', line 257

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


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/mustache.rb', line 192

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`.



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

def self.view_namespace
  @view_namespace || Object
end

.view_namespace=(namespace) ⇒ Object



173
174
175
# File 'lib/mustache.rb', line 173

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 “.”



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

def self.view_path
  @view_path ||= '.'
end

.view_path=(path) ⇒ Object



183
184
185
# File 'lib/mustache.rb', line 183

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!”



308
309
310
# File 'lib/mustache.rb', line 308

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

#[]=(key, value) ⇒ Object



312
313
314
# File 'lib/mustache.rb', line 312

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

#compiled?Boolean

Has this instance or its class already compiled a template?

Returns:

  • (Boolean)


244
245
246
# File 'lib/mustache.rb', line 244

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.



298
299
300
# File 'lib/mustache.rb', line 298

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

#raise_on_context_miss?Boolean

Instance level version of ‘Mustache.raise_on_context_miss?`

Returns:

  • (Boolean)


290
291
292
# File 'lib/mustache.rb', line 290

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}.



318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/mustache.rb', line 318

def render(data = template, ctx = {})
  tpl = templateify(data)

  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.



97
98
99
# File 'lib/mustache.rb', line 97

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

#templateObject

The template can be set at the instance level.



281
282
283
# File 'lib/mustache.rb', line 281

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

#template=(template) ⇒ Object



285
286
287
# File 'lib/mustache.rb', line 285

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

#templateify(obj) ⇒ Object



276
277
278
# File 'lib/mustache.rb', line 276

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