class ZTK::Template

Erubis Templating Class

Given a template like this (i.e. “template.erb”):

This is a test template!
<%= @variable %>

We can do this:

ZTK::Template.render("template.erb", { :variable => "Hello World" })

And get:

This is a test template!
Hello World

@author Zachary Patten <zpatten AT jovelabs DOT io>

Public Class Methods

do_not_edit_notice(options={}) click to toggle source

Renders a “DO NOT EDIT” notice for placement in generated files.

@param [Hash] options Options hash. @option options [String] :message An optional message to display in the notice. @option options [String] :char The comment character; defaults to '#'.

@return [String] The rendered noticed.

# File lib/ztk/template.rb, line 58
def do_not_edit_notice(options={})
  message = options[:message]
  char    = (options[:char] || '#')
  notice  = Array.new

  notice << char
  notice << "#{char} WARNING: AUTOMATICALLY GENERATED FILE; DO NOT EDIT!"
  if !message.nil?
    notice << char
    notice << "#{char} #{message}"
  end
  notice << char
  notice << "#{char} Generated @ #{Time.now.utc}"
  notice << char

  notice.join("\n") + "\n"
end
render(template, context=nil) click to toggle source

Renders a template to a string.

@param [String] template The ERB template to process. @param [Hash] context A hash containing key-pairs, for which the keys are turned into global variables with their respective values.

@return [String] The evaulated template content.

# File lib/ztk/template.rb, line 37
def render(template, context=nil)
  render_template(load_template(template), context)
end
string(template, context=nil) click to toggle source

Renders a string to a string.

@param [String] template The ERB template to process. @param [Hash] context A hash containing key-pairs, for which the keys are turned into global variables with their respective values.

@return [String] The evaulated template content.

# File lib/ztk/template.rb, line 47
def string(template, context=nil)
  render_template(template, context)
end

Private Class Methods

load_template(template) click to toggle source

Loads the template files contents.

# File lib/ztk/template.rb, line 80
def load_template(template)
  IO.read(template).chomp
end
render_template(template, context={}) click to toggle source

Renders the template through Erubis.

# File lib/ztk/template.rb, line 85
def render_template(template, context={})
  Erubis::Eruby.new(template).evaluate(context)
end