根据胡子RFC
A {{name}} tag in a basic template will try to find the name key in
the current context. If there is no name key,nothing will be
rendered.
因此我期待这样:
- var template = '{{#anArray}}{{aString}}{{/anArray}}';
- var json = {
- "aString":"ABC","anArray": [1,{"aString":"DEF"}]
- };
给我一次渲染:
- "DEF"
但是,mustache.js会在父级范围内查找值.这给了我
- "ABCDEF"
上下文实际上意味着包括所有父母范围吗?
解决方法
简短回答:是的.
更长的答案. Context.prototype.lookup执行while循环,在当前上下文中查找标记,并且它是父上下文,同时存在父上下文.
相关的代码:
- Context.prototype.lookup = function (name) {
- var value = this._cache[name];
- if (!value) {
- if (name === ".") {
- value = this.view;
- } else {
- var context = this;
- //Iterate ancestor contexts
- while (context) {
- if (name.indexOf(".") > 0) {
- var names = name.split("."),i = 0;
- value = context.view;
- while (value && i < names.length) {
- value = value[names[i++]];
- }
- } else {
- value = context.view[name];
- }
- if (value != null) {
- break;
- }
- context = context.parent;
- }
- }
- this._cache[name] = value;
- }
- if (typeof value === "function") {
- value = value.call(this.view);
- }
- return value;
- };