Class: Stipa::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/stipa/template.rb

Overview

ERB template engine with layout support and Vue.js integration helpers.

Usage:

engine = Stipa::Template.new(views_dir: 'views')
html   = engine.render('home', locals: { user: 'Alice' })

With an explicit layout:

html = engine.render('home', layout: 'layouts/admin')

Without a layout (useful for partials / API fragments):

html = engine.render('_row', locals: { item: obj }, layout: false)

Directory conventions:

views/
  layouts/
    application.html.erb   ← default layout
  home.html.erb
  users/
    show.html.erb
  _sidebar.html.erb        ← partials start with _

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(views_dir:) ⇒ Template

Returns a new instance of Template.



28
29
30
# File 'lib/stipa/template.rb', line 28

def initialize(views_dir:)
  @views_dir = File.expand_path(views_dir)
end

Instance Attribute Details

#views_dirObject (readonly)

Returns the value of attribute views_dir.



26
27
28
# File 'lib/stipa/template.rb', line 26

def views_dir
  @views_dir
end

Instance Method Details

#render(template, locals: {}, layout: :default) ⇒ Object

Render a template, optionally wrapped in a layout.

template - name like ‘home’, ‘users/show’, or ‘home.html.erb’ locals - Hash of variables made available inside the template layout - :default → auto-detect views/layouts/application.html.erb

a String  → explicit layout name (same resolution as template)
false     → no layout


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

def render(template, locals: {}, layout: :default)
  ctx = ViewContext.new(self)
  locals.each { |k, v| ctx._set_local(k, v) }

  content = render_file(resolve(template), ctx)

  layout_path = resolve_layout(layout)
  if layout_path && File.exist?(layout_path)
    ctx._set_content(content)
    render_file(layout_path, ctx)
  else
    content
  end
end