Erb_templates

require 'erb'

class Templates
  def initialize(&bl)
    @tmp = {}
    instance_exec &bl if bl
  end
 
  def (name, str) = ( @tmp[name] = ERB.new str )
  def x(name, bnd=TOPLEVEL_BINDING) = ( @tmp[name].result(bnd) )
end

def tmp(&bl) = ( Templates.new(&bl) )


# Examples =====================================================

Out = tmp {
   :data, %(<%= name %> is <%= age %> years old.)
   :prov, <<~TEMPLATE
      <% test  %>
      <% 5.times { puts name } %>
  TEMPLATE
}

name = 'Laban'
age = 8

p Out.x :data # => "Laban is 8 years old."

def test
  name, age = 'Anki', 88
  p Out.x :data # "Laban is 8 years old."
  p Out.x :data, binding # "Anki is 88 years old."
end

test

# --------

p '-' * 50

Out.x :prov
# =>
# "Laban is 8 years old."
# "Anki is 88 years old."
# Laban
# Laban
# Laban
# Laban
# Laban

Made a module Link to heading

# filename: mw_template.rb
module Template
  require 'erb'

  class Tmp
    def initialize(&bl) = ( @tmp = {}; instance_exec &bl if bl )
    def (name, str) = ( @tmp[name] = ERB.new str )
    
    def method_missing(name, bnd=TOPLEVEL_BINDING)
      @tmp[name] ? @tmp[name].result(bnd) : super
    end
  end

  def tmp(&bl) = ( Tmp.new(&bl) )
  
  module_function :tmp
end

Usage: Link to heading

require 'mw_template.rb'

Tmp = Template.tmp {
   :prov, %(Name: <%= name %>, Age: <%= age %>)
   :test, %(<% test %>)
}

name, age = 'Olle', 8
p Tmp.prov # => "Name: Olle, Age: 8"

# binding
def test
  name, age = 'Kajsa', 4
  p Tmp.prov(binding)
end

Tmp.test # => "Name: Kajsa, Age: 4"