class Roger::Template

Roger template processing class

Attributes

current_tilt_template[R]

The current tilt template being used

data[RW]

Store the frontmatter

source[RW]

The source

source_path[RW]

The path to the source file for this template

Public Class Methods

new(source, context = nil, options = {}) click to toggle source

@option options [String,Pathname] :source_path The path to

the source of the template being processed
# File lib/roger/template.rb, line 41
def initialize(source, context = nil, options = {})
  @context = context

  self.source_path = options[:source_path]
  self.data, self.source = extract_front_matter(source)

  @templates = Tilt.templates_for(source_path)
end
open(path, context = nil, options = {}) click to toggle source
# File lib/roger/template.rb, line 34
def open(path, context = nil, options = {})
  new(File.read(path), context, options.update(source_path: path))
end

Public Instance Methods

real_source_path() click to toggle source

Actual path on disk, nil if it doesn't exist The nil case is mostly used with inline rendering.

# File lib/roger/template.rb, line 58
def real_source_path
  return @_real_source_path if @_real_source_path_cached

  @_real_source_path_cached = true
  @_real_source_path = if File.exist?(source_path)
                         Pathname.new(source_path).realpath
                       end
end
render(locals = {}, &block) click to toggle source
# File lib/roger/template.rb, line 50
def render(locals = {}, &block)
  @templates.inject(source) do |src, template|
    render_with_tilt_template(template, src, locals, &block)
  end
end

Protected Instance Methods

extract_front_matter(source) click to toggle source

Get the front matter portion of the file and extract it.

# File lib/roger/template.rb, line 90
def extract_front_matter(source)
  fm_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m

  return [{}, source] unless match = source.match(fm_regex)

  source = source.sub(fm_regex, "")

  begin
    data = (YAML.safe_load(match[1]) || {}).inject({}) do |memo, (k, v)|
      memo[k.to_sym] = v
      memo
    end
  rescue *YAML_ERRORS => e
    puts "YAML Exception: #{e.message}"
    return false
  end

  [data, source]
rescue
  [{}, source]
end
render_with_tilt_template(template_class, src, locals) { || ... } click to toggle source

Render source with a specific tilt template class

# File lib/roger/template.rb, line 70
def render_with_tilt_template(template_class, src, locals, &_block)
  @current_tilt_template = template_class
  template = template_class.new(source_path) { src }

  block_content = if block_given?
                    yield
                  else
                    ""
                  end

  template.render(@context, locals) do |name|
    if name
      @context._content_for_blocks[name]
    else
      block_content
    end
  end
end