Module: Middleman::CoreExtensions::Rendering::InstanceMethods

Defined in:
lib/middleman-core/core_extensions/rendering.rb

Overview

Rendering instance methods

Instance Method Summary collapse

Instance Method Details

#current_engineSymbol?

The currently rendering engine

Returns:



406
407
408
# File 'lib/middleman-core/core_extensions/rendering.rb', line 406

def current_engine
  @_current_engine ||= nil
end

#current_engine=(v) ⇒ Symbol?

The currently rendering engine

Returns:



412
413
414
# File 'lib/middleman-core/core_extensions/rendering.rb', line 412

def current_engine=(v)
  @_current_engine = v
end

#fetch_layout(engine, opts) ⇒ String

Find a layout for a given engine

Parameters:

Returns:

  • (String)


318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/middleman-core/core_extensions/rendering.rb', line 318

def fetch_layout(engine, opts)
  # The layout name comes from either the system default or the options
  local_layout = opts.has_key?(:layout) ? opts[:layout] : config[:layout]
  return false unless local_layout

  # Look for engine-specific options
  engine_options = respond_to?(engine) ? send(engine) : {}

  # The engine for the layout can be set in options, engine_options or passed
  # into this method
  layout_engine = if opts.has_key?(:layout_engine)
    opts[:layout_engine]
  elsif engine_options.has_key?(:layout_engine)
    engine_options[:layout_engine]
  else
    engine
  end

  # Automatic mode
  if local_layout == :_auto_layout
    # Look for :layout of any extension
    # If found, use it. If not, continue
    locate_layout(:layout, layout_engine) || false
  else
    # Look for specific layout
    # If found, use it. If not, error.
    if layout_path = locate_layout(local_layout, layout_engine)
      layout_path
    else
      raise ::Middleman::CoreExtensions::Rendering::TemplateNotFound, "Could not locate layout: #{local_layout}"
    end
  end
end

#locate_layout(name, preferred_engine = nil) ⇒ String

Find a layout on-disk, optionally using a specific engine

Parameters:

  • name (String)
  • preferred_engine (Symbol) (defaults to: nil)

Returns:

  • (String)


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/middleman-core/core_extensions/rendering.rb', line 356

def locate_layout(name, preferred_engine=nil)
  # Whether we've found the layout
  layout_path = false

  resolve_opts = {}
  resolve_opts[:preferred_engine] = preferred_engine if !preferred_engine.nil?

  # Check layouts folder
  layout_path = resolve_template(File.join(config[:layouts_dir], name.to_s), resolve_opts)

  # If we didn't find it, check root
  layout_path = resolve_template(name, resolve_opts) unless layout_path

  # Return the path
  layout_path
end

#options_for_ext(ext) ⇒ Hash

Get a hash of configuration options for a given file extension, from config.rb

Parameters:

  • ext (String)

Returns:

  • (Hash)


295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/middleman-core/core_extensions/rendering.rb', line 295

def options_for_ext(ext)
  # Read options for extension from config/Tilt or cache
  cache.fetch(:options_for_ext, ext) do
    options = {}

    # Find all the engines which handle this extension in tilt. Look for
    # config variables of that name and merge it
    extension_class = ::Tilt[ext]
    ::Tilt.mappings.each do |mapping_ext, engines|
      next unless engines.include? extension_class
      engine_options = config[mapping_ext.to_sym] || {}
      options.merge!(engine_options)
    end

    options
  end
end

#render(engine, data, options = {}, &block) ⇒ String

Sinatra/Padrino compatible render method signature referenced by some view helpers. Especially partials.

Parameters:

  • engine (String, Symbol)
  • data (String, Symbol)
  • options (Hash) (defaults to: {})

Returns:

  • (String)

Raises:



187
188
189
190
191
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
# File 'lib/middleman-core/core_extensions/rendering.rb', line 187

def render(engine, data, options={}, &block)
  data = data.to_s

  locals = options[:locals]

  found_partial = false
  resolve_opts = { try_without_underscore: true }

  # If the path is known to the sitemap
  if resource = sitemap.find_resource_by_path(current_path)
    current_dir = File.dirname(resource.source_file)
    resolve_opts[:preferred_engine] = File.extname(resource.source_file)[1..-1].to_sym

    # Look for partials relative to the current path
    relative_dir = File.join(current_dir.sub(%r{^#{Regexp.escape(self.source_dir)}/?}, ''), data)

    found_partial = resolve_template(relative_dir, resolve_opts)
  end

  # Look in the partials_dir for the partial with the current engine
  if !found_partial
    partials_path = File.join(config[:partials_dir], data)
    found_partial = resolve_template(partials_path, resolve_opts)
  end

  raise ::Middleman::CoreExtensions::Rendering::TemplateNotFound, "Could not locate partial: #{data}" unless found_partial

  # Render the partial if found, otherwide throw exception
  render_individual_file(found_partial, locals, options, self, &block)
end

#render_individual_file(path, locs = {}, opts = {}, context = self, &block) ⇒ String

Render an on-disk file. Used for everything, including layouts.

Parameters:

  • path (String, Symbol)
  • locs (Hash) (defaults to: {})
  • opts (Hash) (defaults to: {})
  • context (Class) (defaults to: self)

Returns:

  • (String)


225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/middleman-core/core_extensions/rendering.rb', line 225

def render_individual_file(path, locs = {}, opts = {}, context = self, &block)
  path = path.to_s

  # Detect the remdering engine from the extension
  extension = File.extname(path)
  engine = extension[1..-1].to_sym

  # Store last engine for later (could be inside nested renders)
  context.current_engine, engine_was = engine, context.current_engine

  # Save current buffer for later
  @_out_buf, _buf_was = '', @_out_buf

  # Read from disk or cache the contents of the file
  body = if opts[:template_body]
    opts.delete(:template_body)
  else
    template_data_for_file(path)
  end

  # Merge per-extension options from config
  extension = File.extname(path)
  options = opts.dup.merge(options_for_ext(extension))
  options[:outvar] ||= '@_out_buf'
  options.delete(:layout)

  # Overwrite with frontmatter options
  options = options.deep_merge(options[:renderer_options]) if options[:renderer_options]

  template_class = Tilt[path]
  # Allow hooks to manipulate the template before render
  self.class.callbacks_for_hook(:before_render).each do |callback|
    newbody = callback.call(body, path, locs, template_class)
    body = newbody if newbody # Allow the callback to return nil to skip it
  end

  # Read compiled template from disk or cache
  template = cache.fetch(:compiled_template, extension, options, body) do
   ::Tilt.new(path, 1, options) { body }
  end

  # Render using Tilt
  content = template.render(context, locs, &block)

  # Allow hooks to manipulate the result after render
  self.class.callbacks_for_hook(:after_render).each do |callback|
    content = callback.call(content, path, locs, template_class)
  end

  output = ::ActiveSupport::SafeBuffer.new ''
  output.safe_concat content
  output
ensure
  # Reset stored buffer
  @_out_buf = _buf_was
  context.current_engine = engine_was
end

#render_template(path, locs = {}, opts = {}, blocks = []) ⇒ String

Render a template, with layout, given a path

Parameters:

  • path (String)
  • locs (Hash) (defaults to: {})
  • opts (Hash) (defaults to: {})

Returns:

  • (String)


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/middleman-core/core_extensions/rendering.rb', line 132

def render_template(path, locs={}, opts={}, blocks=[])
  extension = File.extname(path)
  engine = extension[1..-1].to_sym

  if defined?(::I18n)
    old_locale = ::I18n.locale
    ::I18n.locale = opts[:lang] if opts[:lang]
  end

  # Use a dup of self as a context so that instance variables set within
  # the template don't persist for other templates.
  context = self.dup
  blocks.each do |block|
    context.instance_eval(&block)
  end

  # Store current locs/opts for later
  @current_locs = locs, @current_opts = opts

  # Keep rendering template until we've used up all extensions. This
  # handles cases like `style.css.sass.erb`
  content = nil
  while ::Tilt[path]
    begin
      opts[:template_body] = content if content
      content = render_individual_file(path, locs, opts, context)
      path = File.basename(path, File.extname(path))
    rescue LocalJumpError
      raise "Tried to render a layout (calls yield) at #{path} like it was a template. Non-default layouts need to be in #{source}/#{config[:layouts_dir]}."
    end
  end

  # If we need a layout and have a layout, use it
  if layout_path = fetch_layout(engine, opts)
    content = render_individual_file(layout_path, locs, opts, context) { content }
  end

  # Return result
  content
ensure
  # Pop all the saved variables from earlier as we may be returning to a
  # previous render (layouts, partials, nested layouts).
  ::I18n.locale = old_locale if defined?(::I18n)
  @content_blocks = nil
  @current_locs = nil
  @current_opts = nil
end

#resolve_template(request_path, options = {}) ⇒ Array<String, Symbol>, Boolean

Find a template on disk given a output path

Parameters:

  • request_path (String)
  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :preferred_engine (Boolean)

    If set, try this engine first, then fall back to any engine.

  • :try_without_underscore (Boolean)

Returns:

  • (Array<String, Symbol>, Boolean)


421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/middleman-core/core_extensions/rendering.rb', line 421

def resolve_template(request_path, options={})
  # Find the path by searching or using the cache
  request_path = request_path.to_s
  cache.fetch(:resolve_template, request_path, options) do
    relative_path = Util.strip_leading_slash(request_path)
    on_disk_path  = File.expand_path(relative_path, self.source_dir)

    # By default, any engine will do
    preferred_engines = ['*']

    # If we're specifically looking for a preferred engine
    if options.has_key?(:preferred_engine)
      extension_class = ::Tilt[options[:preferred_engine]]
      matched_exts = []

      # Get a list of extensions for a preferred engine
      matched_exts = ::Tilt.mappings.select do |ext, engines|
        engines.include? extension_class
      end.keys

      # Prefer to look for the matched extensions
      unless matched_exts.empty?
        preferred_engines.unshift('{' + matched_exts.join(',') + '}')
      end
    end

    search_paths = preferred_engines.flat_map do |preferred_engine|
      path_with_ext = on_disk_path + '.' + preferred_engine
      paths = [path_with_ext]
      if options[:try_without_underscore]
        paths << path_with_ext.sub(relative_path, relative_path.sub(/^_/, '').sub(/\/_/, '/'))
      end
      paths
    end

    found_path = nil
    search_paths.each do |path_with_ext|
      found_path = Dir[path_with_ext].find do |path|
        ::Tilt[path]
      end
      break if found_path
    end

    # If we found one, return it and the found engine
    if found_path
      found_path
    elsif File.exists?(on_disk_path)
      on_disk_path
    else
      false
    end
  end
end

#template_data_for_file(path) ⇒ String

Get the template data from a path

Parameters:

  • path (String)

Returns:

  • (String)


286
287
288
# File 'lib/middleman-core/core_extensions/rendering.rb', line 286

def template_data_for_file(path)
  File.read(File.expand_path(path, source_dir))
end

#template_extensions(extension_map = nil) ⇒ Hash

Add or overwrite a default template extension

Parameters:

  • extension_map (Hash) (defaults to: nil)

Returns:

  • (Hash)


120
121
122
123
124
# File 'lib/middleman-core/core_extensions/rendering.rb', line 120

def template_extensions(extension_map=nil)
  @_template_extensions ||= {}
  @_template_extensions.merge!(extension_map) if extension_map
  @_template_extensions
end

#wrap_layout(layout_name, &block)

This method returns an undefined value.

Allow layouts to be wrapped in the contents of other layouts

Parameters:

  • layout_name (String, Symbol)


376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/middleman-core/core_extensions/rendering.rb', line 376

def wrap_layout(layout_name, &block)
  # Save current buffer for later
  @_out_buf, _buf_was = '', @_out_buf

  layout_path = locate_layout(layout_name, self.current_engine)

  extension = File.extname(layout_path)
  engine = extension[1..-1].to_sym

  # Store last engine for later (could be inside nested renders)
  self.current_engine, engine_was = engine, self.current_engine

  begin
    content = if block_given?
      capture_html(&block)
    else
      ''
    end
  ensure
    # Reset stored buffer
    @_out_buf = _buf_was
  end

  concat_safe_content render_individual_file(layout_path, @current_locs || {}, @current_opts || {}, self) { content }
ensure
  self.current_engine = engine_was
end