Debian Codegraph @

lib/mustache.rb

raw symbols SCIP
1 require 'mustache/enumerable'
2 require 'mustache/template'
3 require 'mustache/context'
4 require 'mustache/settings'
5 require 'mustache/utils'
6
7 # Mustache is the base class from which your Mustache subclasses
8 # should inherit (though it can be used on its own).
9 #
10 # The typical Mustache workflow is as follows:
11 #
12 # * Create a Mustache subclass: class Stats < Mustache
13 # * Create a template: stats.mustache
14 # * Instantiate an instance: view = Stats.new
15 # * Render that instance: view.render
16 #
17 # You can skip the instantiation by calling `Stats.render` directly.
18 #
19 # While Mustache will do its best to load and render a template for
20 # you, this process is completely customizable using a few options.
21 #
22 # All settings can be overriden at the class level.
23 #
24 # For example, going with the above example, we can use
25 # `Stats.template_path = "/usr/local/templates"` to specify the path
26 # Mustache uses to find templates.
27 #
28 # Here are the available options:
29 #
30 # * template_path
31 #
32 # The `template_path` setting determines the path Mustache uses when
33 # looking for a template. By default it is "."
34 # Setting it to /usr/local/templates, for example, means (given all
35 # other settings are default) a Mustache subclass `Stats` will try to
36 # load /usr/local/templates/stats.mustache
37 #
38 # * template_extension
39 #
40 # The `template_extension` is the extension Mustache uses when looking
41 # for template files. By default it is "mustache"
42 #
43 # * template_file
44 #
45 # You can tell Mustache exactly which template to use with this
46 # setting. It can be a relative or absolute path.
47 #
48 # * template
49 #
50 # Sometimes you want Mustache to render a string, not a file. In those
51 # cases you may set the `template` setting. For example:
52 #
53 # >> Mustache.render("Hello {{planet}}", :planet => "World!")
54 # => "Hello World!"
55 #
56 # The `template` setting is also available on instances.
57 #
58 # view = Mustache.new
59 # view.template = "Hi, {{person}}!"
60 # view[:person] = 'Mom'
61 # view.render # => Hi, mom!
62 #
63 # * view_namespace
64 #
65 # To make life easy on those developing Mustache plugins for web frameworks or
66 # other libraries, Mustache will attempt to load view classes (i.e. Mustache
67 # subclasses) using the `view_class` class method. The `view_namespace` tells
68 # Mustache under which constant view classes live. By default it is `Object`.
69 #
70 # * view_path
71 #
72 # Similar to `template_path`, the `view_path` option tells Mustache where to look
73 # for files containing view classes when using the `view_class` method.
74 #
75 class Mustache
76
77 # Initialize a new Mustache instance.
78 #
79 # @param [Hash] options An options hash
80 # @option options [String] template_path
81 # @option options [String] template_extension
82 # @option options [String] template_file
83 # @option options [String] template
84 # @option options [String] view_namespace
85 # @option options [String] view_path
86 def initialize(options = {})
87 @options = options
88
89 initialize_settings
90 end
91
92 # Instantiates an instance of this class and calls `render` with
93 # the passed args.
94 #
95 # @return A rendered String version of a template.
96 def self.render(*args)
97 new.render(*args)
98 end
99
100 # Parses our fancy pants template file and returns normal file with
101 # all special {{tags}} and {{#sections}}replaced{{/sections}}.
102 #
103 # @example Render view
104 # @view.render("Hi {{thing}}!", :thing => :world)
105 #
106 # @example Set view template and then render
107 # View.template = "Hi {{thing}}!"
108 # @view = View.new
109 # @view.render(:thing => :world)
110 #
111 # @param [String,Hash] data A String template or a Hash context.
112 # If a Hash is given, we'll try to figure
113 # out the template from the class.
114 # @param [Hash] ctx A Hash context if `data` is a String template.
115 # @return [String] Returns a rendered version of a template.
116 def render(data = template, ctx = {})
117 case data
118 when Hash
119 ctx = data
120 when Symbol
121 self.template_name = data
122 end
123
124 tpl = case data
125 when Hash
126 templateify(template)
127 when Symbol
128 templateify(template)
129 else
130 templateify(data)
131 end
132
133 return tpl.render(context) if ctx == {}
134
135 begin
136 context.push(ctx)
137 tpl.render(context)
138 ensure
139 context.pop
140 end
141 end
142
143 # Context accessors.
144 #
145 # @example Context accessors
146 # view = Mustache.new
147 # view[:name] = "Jon"
148 # view.template = "Hi, {{name}}!"
149 # view.render # => "Hi, Jon!"
150 def [](key)
151 context[key.to_sym]
152 end
153
154 def []=(key, value)
155 context[key.to_sym] = value
156 end
157
158 # A helper method which gives access to the context at a given time.
159 # Kind of a hack for now, but useful when you're in an iterating section
160 # and want access to the hash currently being iterated over.
161 def context
162 @context ||= Context.new(self)
163 end
164
165 # Given a file name and an optional context, attempts to load and
166 # render the file as a template.
167 def self.render_file(name, context = {})
168 render(partial(name), context)
169 end
170
171 # Given a file name and an optional context, attempts to load and
172 # render the file as a template.
173 def render_file(name, context = {})
174 self.class.render_file(name, context)
175 end
176
177 # Given a name, attempts to read a file and return the contents as a
178 # string. The file is not rendered, so it might contain
179 # {{mustaches}}.
180 #
181 # Call `render` if you need to process it.
182 def self.partial(name)
183 self.new.partial(name)
184 end
185
186 # Override this in your subclass if you want to do fun things like
187 # reading templates from a database. It will be rendered by the
188 # context, so all you need to do is return a string.
189 def partial(name)
190 path = "#{template_path}/#{name}.#{template_extension}"
191
192 begin
193 File.read(path)
194 rescue
195 raise if raise_on_context_miss?
196 ""
197 end
198 end
199
200 # Override this to provide custom escaping.
201 # By default it uses `CGI.escapeHTML`.
202 #
203 # @example Overriding #escape
204 # class PersonView < Mustache
205 # def escape(value)
206 # my_html_escape_method(value.to_s)
207 # end
208 # end
209 #
210 # @param [Object] value Value to escape.
211 # @return [String] Escaped content.
212 def escape(value)
213 self.escapeHTML(value.to_s)
214 end
215
216 # Override this to provide custom escaping.
217 #
218 # @example Overriding #escapeHTML
219 # class PersonView < Mustache
220 # def escapeHTML(str)
221 # my_html_escape_method(str)
222 # end
223 # end
224 #
225 # @deprecated Use {#escape} instead.
226 #
227 # Note that {#escape} can receive any kind of object.
228 # If your override logic is expecting a string, you will
229 # have to call to_s on it yourself.
230 # @param [String] str String to escape.
231 # @return [String] Escaped HTML.
232 def escapeHTML(str)
233 CGI.escapeHTML(str)
234 end
235
236 # Has this instance or its class already compiled a template?
237 def compiled?
238 (@template && @template.is_a?(Template)) || self.class.compiled?
239 end
240
241
242 private
243
244
245 # When given a symbol or string representing a class, will try to produce an
246 # appropriate view class.
247 #
248 # @example
249 # Mustache.view_namespace = Hurl::Views
250 # Mustache.view_class(:Partial) # => Hurl::Views::Partial
251 def self.view_class(name)
252 name = classify(name.to_s)
253
254 # Emptiness begets emptiness.
255 return Mustache if name.to_s.empty?
256
257 name = "#{view_namespace}::#{name}"
258 const = rescued_const_get(name)
259
260 return const if const
261
262 const_from_file(name)
263 end
264
265 def self.rescued_const_get name
266 const_get(name, true) || Mustache
267 rescue NameError
268 nil
269 end
270
271 def self.const_from_file name
272 file_name = underscore(name)
273 file_path = "#{view_path}/#{file_name}.rb"
274
275 return Mustache unless File.exist?(file_path)
276
277 require file_path.chomp('.rb')
278 rescued_const_get(name)
279 end
280
281 # Has this template already been compiled? Compilation is somewhat
282 # expensive so it may be useful to check this before attempting it.
283 def self.compiled?
284 @template.is_a? Template
285 end
286
287
288 # template_partial => TemplatePartial
289 # template/partial => Template::Partial
290 def self.classify(underscored)
291 Mustache::Utils::String.new(underscored).classify
292 end
293
294 # TemplatePartial => template_partial
295 # Template::Partial => template/partial
296 # Takes a string but defaults to using the current class' name.
297 def self.underscore(classified = name)
298 classified = superclass.name if classified.to_s.empty?
299
300 Mustache::Utils::String.new(classified).underscore(view_namespace)
301 end
302
303 # @param [Template,String] obj Turns `obj` into a template
304 # @param [Hash] options Options for template creation
305 def self.templateify(obj, options = {})
306 obj.is_a?(Template) ? obj : Template.new(obj, options)
307 end
308
309 def templateify(obj)
310 opts = {:partial_resolver => self.method(:partial)}
311 opts.merge!(@options) if @options.is_a?(Hash)
312 self.class.templateify(obj, opts)
313 end
314
315 # Return the value of the configuration setting on the superclass, or return
316 # the default.
317 #
318 # @param [Symbol] attr_name Name of the attribute. It should match
319 # the instance variable.
320 # @param [Object] default Default value to use if the superclass does
321 # not respond.
322 #
323 # @return Inherited or default configuration setting.
324 def self.inheritable_config_for(attr_name, default)
325 superclass.respond_to?(attr_name) ? superclass.send(attr_name) : default
326 end
327 end