Skip to content

Instantly share code, notes, and snippets.

@stoffie
Last active October 11, 2015 15:34
Show Gist options
  • Select an option

  • Save stoffie/0b9cc83c7bc646ea29b9 to your computer and use it in GitHub Desktop.

Select an option

Save stoffie/0b9cc83c7bc646ea29b9 to your computer and use it in GitHub Desktop.
solo ruby template engine
module Solo;
module HTML
attr_reader :indent
attr_reader :indent_string
def self.define_element (tag)
define_method tag.to_sym do |*args, &b|
add_tabs
@output += "<"+ tag + ">"
if b.nil?
@output += args[0].to_s
@output += "</" + tag + ">"
else
add_newline
@indent_level += 1
b.call
@indent_level -= 1
add_tabs
@output += "</" + tag + ">"
end
add_newline
end
end
define_element "html"
define_element "p"
define_element "a"
def comment (text)
add_tabs
@output += "<!-- " + text + "-->"
add_newline
end
def doctype
add_tabs
@output += "<!DOCTYPE html>"
add_newline
end
def render
@indent = indent || true
@indent_string = indent_string || "\t"
@indent_level = 0
@output = ""
yield
@output
end
def add_tabs
if @indent
@output += @indent_string * @indent_level
end
end
def add_newline
@output += "\n" if @indent
end
end
class HTMLRenderer
include HTML
end
end
solo = Solo::HTMLRenderer.new
render = solo.render do
solo.html "peso"
solo.html "del tutto"
solo.html do
solo.html "nested peso"
end
end
puts "here is the render:", render.inspect
include Solo::HTML
render = render do
doctype
html do
p "nested peso"
comment "er comment"
p do
comment "bene"
a "lol"
a "nope"
end
end
end
puts "here is the render:", render.inspect
puts render
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment