Skip to content

Commit 79a8e2f

Browse files
authored
refactor: move expressionAttributeValueURL check to separate function (#1206)
1 parent 542b139 commit 79a8e2f

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

generator/generator.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1344,7 +1344,7 @@ func (g *generator) writeExpressionAttribute(indentLevel int, elementName string
13441344
}
13451345
attrKey := html.EscapeString(attr.Key.String())
13461346
// Value.
1347-
if (elementName == "a" && attrKey == "href") || (elementName == "form" && attrKey == "action") {
1347+
if isExpressionAttributeValueURL(elementName, attrKey) {
13481348
if err := g.writeExpressionAttributeValueURL(indentLevel, attr); err != nil {
13491349
return err
13501350
}
@@ -1789,3 +1789,20 @@ func stripTypes(parameters string) string {
17891789
}
17901790
return strings.Join(variableNames, ", ")
17911791
}
1792+
1793+
func isExpressionAttributeValueURL(elementName, attrName string) bool {
1794+
var elementAttributeLookup = map[string]string{
1795+
"a": "href",
1796+
"form": "action",
1797+
"link": "href",
1798+
"object": "data",
1799+
}
1800+
expectedAttribute, exists := elementAttributeLookup[elementName]
1801+
if !exists {
1802+
return false
1803+
}
1804+
if attrName != expectedAttribute {
1805+
return false
1806+
}
1807+
return true
1808+
}

generator/generator_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,38 @@ templ Hello(name string) {
7070
t.Errorf("expected an expression for the package name, template signature (Hello) and for the if (nam), got %#v", op.SourceMap.Expressions)
7171
}
7272
}
73+
74+
func TestIsExpressionAttributeValueURL(t *testing.T) {
75+
testCases := []struct {
76+
elementName string
77+
attrName string
78+
expectedOutput bool
79+
}{
80+
{
81+
elementName: "a",
82+
attrName: "href",
83+
expectedOutput: true,
84+
},
85+
{
86+
elementName: "a",
87+
attrName: "class",
88+
expectedOutput: false,
89+
},
90+
{
91+
elementName: "div",
92+
attrName: "class",
93+
expectedOutput: false,
94+
},
95+
{
96+
elementName: "p",
97+
attrName: "href",
98+
expectedOutput: false,
99+
},
100+
}
101+
102+
for _, testCase := range testCases {
103+
if output := isExpressionAttributeValueURL(testCase.elementName, testCase.attrName); output != testCase.expectedOutput {
104+
t.Errorf("expected %t got %t", testCase.expectedOutput, output)
105+
}
106+
}
107+
}

0 commit comments

Comments
 (0)