From 3a5e7a0a4f99390133d657eb30064c7ebd633f2e Mon Sep 17 00:00:00 2001 From: goring <67476208+goring@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:05:54 +0100 Subject: [PATCH] Add support for single quoted attrs --- elem.go | 17 ++++++++++++++--- elements_test.go | 9 +++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/elem.go b/elem.go index 7f57d07..9ee87e2 100644 --- a/elem.go +++ b/elem.go @@ -194,11 +194,22 @@ func (e *Element) renderAttrTo(attrName string, builder *strings.Builder) { } } else { // regular attribute has a name and a value + attrVal := e.Attrs[attrName] + + // A necessary check to to avoid adding extra quotes around values that are already single-quoted + // An example is '{"quantity": 5}' + isSingleQuoted := strings.HasPrefix(attrVal, "'") && strings.HasSuffix(attrVal, "'") + builder.WriteString(` `) builder.WriteString(attrName) - builder.WriteString(`="`) - builder.WriteString(e.Attrs[attrName]) - builder.WriteString(`"`) + builder.WriteString(`=`) + if !isSingleQuoted { + builder.WriteString(`"`) + } + builder.WriteString(attrVal) + if !isSingleQuoted { + builder.WriteString(`"`) + } } } diff --git a/elements_test.go b/elements_test.go index 426b968..15d8f40 100644 --- a/elements_test.go +++ b/elements_test.go @@ -687,3 +687,12 @@ func TestCSS(t *testing.T) { el := CSS(cssContent) assert.Equal(t, expected, el.Render()) } + +func TestSingleQuote(t *testing.T) { + expected := `
` + el := Div(attrs.Props{ + "data-values": `'{"quantity": 5}'`, + }) + actual := el.Render() + assert.Equal(t, expected, actual) +}