【问题标题】:Iterating over arrays with mustache用小胡子迭代数组
【发布时间】:2010-10-17 19:35:13
【问题描述】:

如何在迭代中获取对当前元素的引用?

{{#my_array}}
    <p>{{__what_goes_here?__}}</p>
{{/my_array}}

我希望我只是忽略了显而易见的事情。

【问题讨论】:

    标签: ruby mustache


    【解决方案1】:

    根据the spec's changelog,隐式迭代器(.)被添加到规范的v1.1.0中。每个至少实现 v1.1.0 的 Mustache 库都应该支持这一点。

    {{#array_of_strings}}<li>{{.}}</li>{{/array_of_strings}}
    

    【讨论】:

    • 注意:数组必须有隐式键才能工作。当您的数组有索引时使用此方法将导致输出单词 Array 的一个实例。
    【解决方案2】:

    来自源代码https://github.com/bobthecow/mustache.php

    /**
     * The {{%IMPLICIT-ITERATOR}} pragma allows access to non-associative array data in an
     * iterable section:
     *
     *     $context = array('items' => array('foo', 'bar', 'baz'));
     *
     * With this template:
     *
     *     {{%IMPLICIT-ITERATOR}}{{#items}}{{.}}{{/items}}
     *
     * Would render as `foobarbaz`.
     *
     * {{%IMPLICIT-ITERATOR}} accepts an optional 'iterator' argument which allows implicit
     * iterator tags other than {{.}} ...
     *
     *     {{%IMPLICIT-ITERATOR iterator=i}}{{#items}}{{i}}{{/items}}
     */
    

    【讨论】:

      【解决方案3】:

      我暂时离开了我的代码,并记得 Ruby 是鸭子类型的。由于我的数组是字符串,我只需要:

      {{#my_array}}
          <p>{{to_s}}</p>
      {{/my_array}}
      

      我将把这个问题留在这里,希望能为其他人节省一些时间。

      【讨论】:

        猜你喜欢
        • 2015-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多