Parcourir la source

Merge pull request #132 from johnnypez/master

Support for Dot Notation, with tests.
tags/0.4.0
Jan Lehnardt il y a 14 ans
Parent
révision
8285a3e42e
4 fichiers modifiés avec 55 ajouts et 6 suppressions
  1. +4
    -0
      examples/dot_notation.html
  2. +18
    -0
      examples/dot_notation.js
  3. +4
    -0
      examples/dot_notation.txt
  4. +29
    -6
      mustache.js

+ 4
- 0
examples/dot_notation.html Voir le fichier

@@ -0,0 +1,4 @@
<h1>{{name}}</h1>
<p>Authors: <ul>{{#authors}}<li>{{.}}</li>{{/authors}}</ul></p>
<p>Price: {{price.currency.symbol}}{{price.value}} {{#price.currency}}{{name}} <b>{{availability.text}}</b>{{/price.currency}}</p>
<p>VAT: {{price.currency.symbol}}{{price.vat}}</p>

+ 18
- 0
examples/dot_notation.js Voir le fichier

@@ -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: '&euro;',
name: 'Euro'
}
},
availability:{
status: true,
text: "In Stock"
}
};

+ 4
- 0
examples/dot_notation.txt Voir le fichier

@@ -0,0 +1,4 @@
<h1>A Book</h1>
<p>Authors: <ul><li>John Power</li><li>Jamie Walsh</li></ul></p>
<p>Price: &euro;200 Euro <b>In Stock</b></p>
<p>VAT: &euro;40</p>

+ 29
- 6
mustache.js Voir le fichier

@@ -269,11 +269,18 @@ var Mustache = function() {
} }


var value; 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") { if(typeof value === "function") {
return value.apply(context); return value.apply(context);
@@ -285,6 +292,22 @@ var Mustache = function() {
return ""; 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 // Utility methods


/* includes tag */ /* includes tag */
@@ -393,4 +416,4 @@ var Mustache = function() {
} }
} }
}); });
}();
}();

Chargement…
Annuler
Enregistrer