diff --git a/examples/dot_notation.html b/examples/dot_notation.html new file mode 100644 index 0000000..749ca3d --- /dev/null +++ b/examples/dot_notation.html @@ -0,0 +1,4 @@ +

{{name}}

+

Authors:

+

Price: {{price.currency.symbol}}{{price.value}} {{#price.currency}}{{name}} {{availability.text}}{{/price.currency}}

+

VAT: {{price.currency.symbol}}{{price.vat}}

\ No newline at end of file diff --git a/examples/dot_notation.js b/examples/dot_notation.js new file mode 100644 index 0000000..f41fafb --- /dev/null +++ b/examples/dot_notation.js @@ -0,0 +1,18 @@ +var dot_notation = { + name: "A Book", + authors: ["John Power", "Jamie Walsh"], + price:{ + value: 200, + vat: function() { + return this.value * 0.2; + }, + currency: { + symbol: '€', + name: 'Euro' + } + }, + availability:{ + status: true, + text: "In Stock" + } +}; \ No newline at end of file diff --git a/examples/dot_notation.txt b/examples/dot_notation.txt new file mode 100644 index 0000000..770e4ce --- /dev/null +++ b/examples/dot_notation.txt @@ -0,0 +1,4 @@ +

A Book

+

Authors:

+

Price: €200 Euro In Stock

+

VAT: €40

diff --git a/mustache.js b/mustache.js index 31566ce..21d5726 100644 --- a/mustache.js +++ b/mustache.js @@ -269,11 +269,18 @@ var Mustache = function() { } var value; - if(is_kinda_truthy(context[name])) { - value = context[name]; - } else if(is_kinda_truthy(this.context[name])) { - value = this.context[name]; - } + + // check for dot notation eg. foo.bar + if(name.match(/([a-z_]+)\./ig)){ + value = is_kinda_truthy(this.walk_context(name, context)); + } + else{ + if(is_kinda_truthy(context[name])) { + value = context[name]; + } else if(is_kinda_truthy(this.context[name])) { + value = this.context[name]; + } + } if(typeof value === "function") { return value.apply(context); @@ -285,6 +292,22 @@ var Mustache = function() { return ""; }, + walk_context: function(name, context){ + var path = name.split('.'); + // if the var doesn't exist in current context, check the top level context + var value_context = (context[path[0]] != undefined) ? context : this.context; + var value = value_context[path.shift()]; + while(value != undefined && path.length > 0){ + value_context = value; + value = value[path.shift()]; + } + // if the value is a function, call it, binding the correct context + if(typeof value === "function") { + return value.apply(value_context); + } + return value; + }, + // Utility methods /* includes tag */ @@ -393,4 +416,4 @@ var Mustache = function() { } } }); -}(); +}(); \ No newline at end of file