Skip to content

Commit 70c5ab6

Browse files
committed
Add dot notation support
1 parent e3ee57d commit 70c5ab6

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

mustache.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,14 @@ func call(v reflect.Value, method reflect.Method) reflect.Value {
369369
// Evaluate interfaces and pointers looking for a value that can look up the name, via a
370370
// struct field, method, or map key, and return the result of the lookup.
371371
func lookup(contextChain []interface{}, name string) reflect.Value {
372+
// dot notation
373+
if name != "." && strings.Contains(name, ".") {
374+
parts := strings.SplitN(name, ".", 2)
375+
376+
v := lookup(contextChain, parts[0])
377+
return lookup([]interface{}{v}, parts[1])
378+
}
379+
372380
defer func() {
373381
if r := recover(); r != nil {
374382
fmt.Printf("Panic while looking up %q: %s\n", name, r)

mustache_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,15 @@ var tests = []Test{
164164

165165
//invalid syntax - https://github.com/hoisie/mustache/issues/10
166166
{`{{#a}}{{#b}}{{/a}}{{/b}}}`, map[string]interface{}{}, "line 1: interleaved closing tag: a"},
167+
168+
//dotted names(dot notation)
169+
{`"{{person.name}}" == "{{#person}}{{name}}{{/person}}"`, map[string]interface{}{"person": map[string]string{"name": "Joe"}}, `"Joe" == "Joe"`},
170+
{`"{{{person.name}}}" == "{{#person}}{{{name}}}{{/person}}"`, map[string]interface{}{"person": map[string]string{"name": "Joe"}}, `"Joe" == "Joe"`},
171+
{`"{{a.b.c.d.e.name}}" == "Phil"`, map[string]interface{}{"a": map[string]interface{}{"b": map[string]interface{}{"c": map[string]interface{}{"d": map[string]interface{}{"e": map[string]string{"name": "Phil"}}}}}}, `"Phil" == "Phil"`},
172+
{`"{{a.b.c}}" == ""`, map[string]interface{}{}, `"" == ""`},
173+
{`"{{a.b.c.name}}" == ""`, map[string]interface{}{"a": map[string]interface{}{"b": map[string]string{}}, "c": map[string]string{"name": "Jim"}}, `"" == ""`},
174+
{`"{{#a}}{{b.c.d.e.name}}{{/a}}" == "Phil"`, map[string]interface{}{"a": map[string]interface{}{"b": map[string]interface{}{"c": map[string]interface{}{"d": map[string]interface{}{"e": map[string]string{"name": "Phil"}}}}}, "b": map[string]interface{}{"c": map[string]interface{}{"d": map[string]interface{}{"e": map[string]string{"name": "Wrong"}}}}}, `"Phil" == "Phil"`},
175+
{`{{#a}}{{b.c}}{{/a}}`, map[string]interface{}{"a": map[string]interface{}{"b": map[string]string{}}, "b": map[string]string{"c": "ERROR"}}, ""},
167176
}
168177

169178
func TestBasic(t *testing.T) {

0 commit comments

Comments
 (0)