diff --git a/examples/templates/helloworld.ru b/examples/templates/helloworld.ru index fa10e4c..ed0b6e7 100644 --- a/examples/templates/helloworld.ru +++ b/examples/templates/helloworld.ru @@ -8,7 +8,7 @@ app = Hyde::Server.new do get "/" do status 200 header "content-type", "text/html" - erb(file("index.rhtml"), { 'localrand' => rand }).run + erubi(file("index.rhtml"), { 'localrand' => rand }).run end end diff --git a/lib/hyde/dsl/constructors_probe.rb b/lib/hyde/dsl/constructors_probe.rb index 4acb3fc..2acf5bf 100644 --- a/lib/hyde/dsl/constructors_probe.rb +++ b/lib/hyde/dsl/constructors_probe.rb @@ -5,12 +5,24 @@ module Hyde # Probe (and subclasses) DSL construct module ProbeConstructors # Create a new erb template - # @see Hyde::Template#new + # @see {Hyde::Template#new} def erb(input, vars = nil) Hyde::Templates::ERB.new(input, vars, parent: @origin) end + + # Create a new erb template using Erubi engine + # @see {Hyde::Template#new} + # @param freeze [Boolean] whether to use frozen string literal + # @param capture [Boolean] whether to enable output capturing + def erubi(input, vars = nil, freeze: true, capture: false) + Hyde::Templates::Erubi.new(input, + vars, + parent: @origin, + freeze: freeze, + capture: capture) + end end end end diff --git a/lib/hyde/template.rb b/lib/hyde/template.rb index 7aaabd5..67ecb27 100644 --- a/lib/hyde/template.rb +++ b/lib/hyde/template.rb @@ -9,6 +9,7 @@ module Hyde # All template engine adapters subclassed from Template module Templates autoload :ERB, "hyde/template/erb" + autoload :Erubi, "hyde/template/erubi" end # Context for template engines @@ -84,7 +85,6 @@ module Hyde def import(filepath) newtemp = self.class.new(filepath, {}, parent: @parent) newtemp.binding = @binding - puts newtemp.pretty_inspect newtemp end diff --git a/lib/hyde/template/erubi.rb b/lib/hyde/template/erubi.rb new file mode 100644 index 0000000..b4e5459 --- /dev/null +++ b/lib/hyde/template/erubi.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'erubi' +require_relative '../template' + +module Hyde + module Templates + # Erubi (ERB) template language adapter + class Erubi < Hyde::Template + # @see {Hyde::Template#new} + def initialize(input, + vars = nil, + parent:, + freeze: true, + capture: false) + super(input, vars, parent: parent) + varname = "_part_#{SecureRandom.hex(10)}" + while @binding.local_variable_defined? varname.to_sym + varname = "_part_#{SecureRandom.hex(10)}" + end + properties = { + filename: input.is_a?(File) ? input.path : "(Inline)", + bufvar: varname, + freeze: freeze + } + engine = capture ? ::Erubi::CaptureEndEngine : ::Erubi::Engine + @template = engine.new(@template, properties) + end + + # Run the template. + def run + @binding.eval(@template.src) + end + end + end +end