dont close void tags

This commit is contained in:
maddalax 2024-09-27 16:18:09 -05:00
parent 0f04094533
commit 1ac2d630c7
2 changed files with 60 additions and 14 deletions

View file

@ -105,6 +105,24 @@ func TestConditional(t *testing.T) {
assert.Equal(t, "<div ></div>", result) assert.Equal(t, "<div ></div>", result)
} }
func TestTagSelfClosing(t *testing.T) {
t.Parallel()
assert.Equal(t, `<input type="text"/>`, Render(
Input("text"),
))
// assert the tag cannot have children
assert.Equal(t, `<input type="text"/>`, Render(
Input("text", Div()),
))
assert.Equal(t, `<div id="test"></div>`, Render(
Div(Id("test")),
))
assert.Equal(t, `<div id="test"><div ></div></div>`, Render(
Div(Id("test"), Div()),
))
}
func BenchmarkMailToStatic(b *testing.B) { func BenchmarkMailToStatic(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
ctx := RenderContext{ ctx := RenderContext{

View file

@ -7,6 +7,26 @@ import (
"strings" "strings"
) )
/*
*
void tags are tags that cannot have children
*/
var voidTags = map[string]bool{
"area": true,
"base": true,
"br": true,
"col": true,
"embed": true,
"hr": true,
"img": true,
"input": true,
"link": true,
"meta": true,
"source": true,
"track": true,
"wbr": true,
}
type RenderContext struct { type RenderContext struct {
builder *strings.Builder builder *strings.Builder
scripts []string scripts []string
@ -79,9 +99,14 @@ func (node *Element) Render(context *RenderContext) {
// close the tag // close the tag
if node.tag != "" { if node.tag != "" {
if voidTags[node.tag] {
context.builder.WriteString("/")
}
context.builder.WriteString(">") context.builder.WriteString(">")
} }
// void elements do not have children
if !voidTags[node.tag] {
// render the children elements that are not attributes // render the children elements that are not attributes
for _, child := range node.children { for _, child := range node.children {
switch child.(type) { switch child.(type) {
@ -95,13 +120,16 @@ func (node *Element) Render(context *RenderContext) {
child.Render(context) child.Render(context)
} }
} }
}
if node.tag != "" { if node.tag != "" {
renderScripts(context) renderScripts(context)
if !voidTags[node.tag] {
context.builder.WriteString("</") context.builder.WriteString("</")
context.builder.WriteString(node.tag) context.builder.WriteString(node.tag)
context.builder.WriteString(">") context.builder.WriteString(">")
} }
}
} }
func renderScripts(context *RenderContext) { func renderScripts(context *RenderContext) {