Module: Tina4::Template

Defined in:
lib/tina4/template.rb

Defined Under Namespace

Classes: ErbEngine, TwigEngine

Constant Summary collapse

TEMPLATE_DIRS =
%w[templates src/templates src/views views].freeze

Class Method Summary collapse

Class Method Details

.add_global(key, value) ⇒ Object



12
13
14
# File 'lib/tina4/template.rb', line 12

def add_global(key, value)
  globals[key.to_s] = value
end

.globalsObject



8
9
10
# File 'lib/tina4/template.rb', line 8

def globals
  @globals ||= {}
end

.render(template_path, data = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/tina4/template.rb', line 16

def render(template_path, data = {})
  full_path = resolve_path(template_path)
  unless full_path && File.exist?(full_path)
    raise "Template not found: #{template_path}"
  end

  content = File.read(full_path)
  ext = File.extname(full_path).downcase
  context = globals.merge(data.transform_keys(&:to_s))

  case ext
  when ".twig", ".html", ".tina4"
    TwigEngine.new(context, File.dirname(full_path)).render(content)
  when ".erb"
    ErbEngine.render(content, context)
  else
    TwigEngine.new(context, File.dirname(full_path)).render(content)
  end
end

.render_error(code, data = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/tina4/template.rb', line 36

def render_error(code, data = {})
  error_dirs = TEMPLATE_DIRS.map { |d| File.join(Dir.pwd, d, "errors") }
  error_dirs << File.join(File.dirname(__FILE__), "templates", "errors")

  context = { "code" => code }.merge(data.transform_keys(&:to_s))

  error_dirs.each do |dir|
    %w[.twig .html .erb].each do |ext|
      path = File.join(dir, "#{code}#{ext}")
      if File.exist?(path)
        content = File.read(path)
        return TwigEngine.new(context, dir).render(content)
      end
    end
  end
  default_error_html(code)
end