Class: Lux::Template

Inherits:
Object show all
Defined in:
lib/lux/template/helper.rb,
lib/lux/template/template.rb

Defined Under Namespace

Classes: Helper

Constant Summary collapse

@@template_cache =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template:, scope:) ⇒ Template

Returns a new instance of Template.



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/lux/template/template.rb', line 45

def initialize template:, scope:
  template = './app/views/' + template if template =~ /^\w/

  @helper = if scope.class == Hash
    # create helper class if only hash given
    Lux::Template::Helper.new(scope)
  else
    scope
  end

  compile_template template
end

Class Method Details

.find_layout(root, layout_template) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/lux/template/template.rb', line 28

def find_layout root, layout_template
  path = Lux.cache.fetch "layout-path-#{root}-#{layout_template}" do
    base1 = '%s/layouts/%s.*' % [root, layout_template]
    base2 = '%s/%s/layout.*' % [root, layout_template]
    path = Dir[base1][0] || Dir[base2][0]

    if path
      path.sub /\.[\w]+$/, ''
    else
      raise Lux::Error.not_found(%[Layout path for #{layout_template} not found. Looked in #{base1} & #{base2}])
    end
  end
end

.helper(scope, name) ⇒ Object



24
25
26
# File 'lib/lux/template/template.rb', line 24

def helper scope, name
  Lux::Template::Helper.new scope, name
end

.render(scope, opts, &block) ⇒ Object

scope is self or any other object

  • methods called in templates will be called from scope

  • scope = Lux::Template::Helper.new self, :main (prepare Rails style helper)

Lux::Template.render(scope, template) Lux::Template.render(scope, template: template, layout: layout_file) Lux::Template.render(scope, layout_template) { layout_data }



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/lux/template/template.rb', line 12

def render scope, opts, &block
  opts = { template: opts } if opts.is_a?(String)
  opts = opts.to_hwia :layout, :template

  if opts.layout
    part_data = render(scope, opts.template)
    new(template: opts.layout, scope: scope).render { part_data }
  else
    new(template: opts.template, scope: scope).render &block
  end
end

Instance Method Details

#renderObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/lux/template/template.rb', line 58

def render
  # global thread safe reference pointer to last temaplte rendered
  # we nned this for inline template render
  Lux.current.files_in_use(@template) do |tpl|
    Lux.log ' ' + tpl.sub('//', '/').magenta
  end

  begin
    data = @tilt.render(@helper) do
      yield if block_given?
    end
  rescue => e
    report_error(e)
  end

  data
end