Skip to content

Commit b9cf48f

Browse files
committed
utils: html_builder
1 parent b8059e8 commit b9cf48f

File tree

1 file changed

+54
-20
lines changed

1 file changed

+54
-20
lines changed

src/utils/html_builder.cr

Lines changed: 54 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,31 +18,65 @@
1818
# -----------------------------------------------------------------------
1919

2020
module MoonScript
21-
class HtmlBuilder
22-
def self.build(*, optimize: Bool, doctype: Bool = true, &)
23-
html = XML.build_fragment(indent: optimize ? nil : " ") do |xml|
24-
builder = new(xml)
25-
with builder yield builder
26-
end
27-
end
21+
class HtmlBuilder
22+
def self.build(*, optimize : Bool, doctype : Bool = true, &)
23+
html =
24+
XML.build_fragment(indent: optimize ? nil : " ") do |xml|
25+
builder = new(xml)
2826

29-
def initialize(@xml: XML::Builder)
27+
with builder yield builder
3028
end
3129

32-
def tag(tag, attributes, &)
33-
@xml.element(tag, attributes) { with self yield }
30+
header =
31+
if doctype
32+
"<!DOCTYPE html>#{optimize ? "" : "\n"}"
3433
end
3534

36-
def script(**attributes, &)
37-
@xml.element("script", **attributes) { with self yield }
38-
end
35+
"#{header}#{html}"
36+
end
3937

40-
def script(**attributes)
41-
script(**attributes) { text("") }
42-
end
38+
def initialize(@xml : XML::Builder)
39+
end
4340

44-
def raw(contents)
45-
@xml.raw(contents)
46-
end
41+
def tag(tag, attributes, &)
42+
@xml.element(tag, attributes) { with self yield }
4743
end
48-
end
44+
45+
def script(**attributes, &)
46+
@xml.element("script", **attributes) { with self yield }
47+
end
48+
49+
def script(**attributes)
50+
script(**attributes) { text("") }
51+
end
52+
53+
def a(**attributes, &)
54+
@xml.element("a", **attributes) { with self yield }
55+
end
56+
57+
def a(**attributes)
58+
a(**attributes) { text("") }
59+
end
60+
61+
def text(contents)
62+
@xml.text(contents)
63+
end
64+
65+
def raw(contents)
66+
@xml.raw(contents)
67+
end
68+
69+
{% for tag in %w(html head body meta link pre code noscript div span h1 h2
70+
h3 title aside article nav strong) %}
71+
def {{tag.id}}(**attributes)
72+
@xml.element("{{tag.id}}", **attributes)
73+
end
74+
75+
def {{tag.id}}(**attributes)
76+
@xml.element("{{tag.id}}", **attributes) do
77+
with self yield
78+
end
79+
end
80+
{% end %}
81+
end
82+
end

0 commit comments

Comments
 (0)