Skip to content

Commit

Permalink
adds support for nested map options:
Browse files Browse the repository at this point in the history
{data: {remote: true, method: "PUT"}}
<data-remote="true" data-method="PUT">
  • Loading branch information
markbates committed Apr 17, 2019
1 parent d22139b commit 57ffdb2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
27 changes: 18 additions & 9 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,27 @@ type Options map[string]interface{}

func (o Options) String() string {
var out = make([]string, 0, len(o))
var tmp = make([]string, 2)
for k, v := range o {
tmp[0] = template.HTMLEscaper(k)
if v != nil {
tmp[1] = fmt.Sprintf("\"%s\"", template.HTMLEscaper(v))
out = append(out, strings.Join(tmp, "="))
} else {
// nil attribute value is interpreted as empty attribute notation
// https://www.w3.org/TR/html5/syntax.html#elements-attributes
out = append(out, tmp[0])
if m, ok := v.(map[string]interface{}); ok {
for mk, mv := range m {
out = append(out, kv(fmt.Sprintf("%s-%s", k, mk), mv))
}
continue
}
out = append(out, kv(k, v))
}
sort.Strings(out)
return strings.Join(out, " ")
}

func kv(k string, v interface{}) string {
var tmp = make([]string, 2)
tmp[0] = template.HTMLEscaper(k)
if v != nil {
tmp[1] = fmt.Sprintf("\"%s\"", template.HTMLEscaper(v))
return strings.Join(tmp, "=")
}
// nil attribute value is interpreted as empty attribute notation
// https://www.w3.org/TR/html5/syntax.html#elements-attributes
return tmp[0]
}
15 changes: 15 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,18 @@ func Test_Options_String_Empty_Attribute(t *testing.T) {
s := o.String()
r.Equal(`checked value="Mark"`, s)
}

func Test_Options_Data_Map(t *testing.T) {
r := require.New(t)
o := tags.Options{
"value": "Mark",
"id": "foo-bar",
"class": "foo bar baz",
"data": map[string]interface{}{
"remote": true,
"method": "PUT",
},
}
s := o.String()
r.Equal(`class="foo bar baz" data-method="PUT" data-remote="true" id="foo-bar" value="Mark"`, s)
}

0 comments on commit 57ffdb2

Please sign in to comment.