【问题标题】:Mustache js takes parent's object scope when none is found in the current one当在当前对象中找不到时,Mustache js 采用父对象范围
【发布时间】:2012-12-27 11:07:41
【问题描述】:

根据胡子RFC

基本模板中的 {{name}} 标签将尝试在 当前上下文。如果没有 name 键,则什么都不会 渲染。

因此,我期望这样:

var template = '{{#anArray}}{{aString}}{{/anArray}}';

var json = {
    "aString":"ABC",
    "anArray": [1,{"aString":"DEF"}]
 };

给我一​​次渲染:

"DEF"

但是 mustache.js 会在父级范围内查找值。这给了我

"ABCDEF"

上下文是否真的意味着包括所有父范围?

http://jsfiddle.net/ZG4zd/20/

【问题讨论】:

    标签: javascript mustache


    【解决方案1】:

    简短回答:是的。

    一个更长的答案。 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;
      };
    

    【讨论】:

    • 那么任何 Mustache 端口都必须相同?我的意思是这不仅仅是 Mustache.js 中的一个特性?
    • @FlavienVolken 我想是的,至少在 pystache 中是一样的。
    • @FlavienVolken ...和红宝石
    • 它是 mustache 规范的一部分,因此任何符合规范的 mustache 实现都会执行相同的上下文查找。
    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多