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,28 +99,36 @@ 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(">")
} }
// render the children elements that are not attributes // void elements do not have children
for _, child := range node.children { if !voidTags[node.tag] {
switch child.(type) { // render the children elements that are not attributes
case *AttributeMap: for _, child := range node.children {
continue switch child.(type) {
case *AttributeR: case *AttributeMap:
continue continue
case *LifeCycle: case *AttributeR:
continue continue
default: case *LifeCycle:
child.Render(context) continue
default:
child.Render(context)
}
} }
} }
if node.tag != "" { if node.tag != "" {
renderScripts(context) renderScripts(context)
context.builder.WriteString("</") if !voidTags[node.tag] {
context.builder.WriteString(node.tag) context.builder.WriteString("</")
context.builder.WriteString(">") context.builder.WriteString(node.tag)
context.builder.WriteString(">")
}
} }
} }