Module: Dimples::Publishable

Included in:
Page, Post, Template
Defined in:
lib/dimples/publishable.rb

Instance Method Summary collapse

Instance Method Details

#render(context = {}, body = nil, use_layout = true) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/dimples/publishable.rb', line 16

def render(context = {}, body = nil, use_layout = true)
  class_name = self.class.name.split('::').last.downcase.to_sym

  context[:site] = @site unless context[:site]
  context[class_name] = self unless context[class_name]

  scope = Object.new

  context.each_pair do |key, value|
    scope.instance_variable_set("@#{key}".to_sym, value)
  end

  proc = Proc.new { |template| contents() }

  renderer = if @path
    extension = File.extname(@path)[1..-1]
    options = @site.config['rendering'][extension] || {}

    Tilt.new(@path, options, &proc)
  else
    Tilt::StringTemplate.new(&proc)
  end

  begin
    output = renderer.render(scope) { body }.strip
    @rendered_contents = output
  rescue RuntimeError, TypeError, NoMethodError, SyntaxError => e
    problem_file = if @path
      @path.gsub(@site.source_paths[:root], '')
    else
      "dynamic #{self.class}"
    end

    raise "Failed to render #{problem_file} - #{e}"
  end

  if use_layout && @layout && @site.templates[@layout]
    output = @site.templates[@layout].render(context, output)
  end

  output
end

#write(path, context = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/dimples/publishable.rb', line 3

def write(path, context = {})
  output = context ? render(context) : contents()

  publish_path = output_file_path(path)
  parent_path = File.dirname(publish_path)

  FileUtils.mkdir_p(parent_path) unless Dir.exist?(parent_path)

  File.open(publish_path, 'w') do |file|
    file.write(output)
  end
end