如何将数据数组渲染成多个小胡子部分?

How to render array of data into multiple mustache partials?

我正在使用 Python 的 pystache(这是标准的 Mustache api)。

这是我的数据结构的示例:

{
  "results": [
    {
      "user": "foo",
      "flags": [
        "a",
        "b",
        "c"
      ]
    },
    { ... }
  ]
}

现在在我的模板中我尝试这样做:

{{#results}}
    {{> stuff}}
{{/results}}

其中 stuff 是部分,部分看起来像这样:

user: {{ user }}
isX: {{ flags.x }}

现在向模板提供数据的是 class,它充当 'view model',因此我可以规范化一些数据并让模板与规范化数据而不是原始数据交互json 数据如上所示。

问题是我不知道如何实现我的视图模型来处理我们循环遍历嵌套数据的事实。

以上例为例,我的原始数据使用字符串数组来表示 flags 值,我希望模板根据值 x 显示 true 或 false出现在标志数组中。

在代码中我可能会尝试这样实现:

class Feed(Presenter):
    def prepare_view(self, **params):
        self.view = View()
        self.view.template_path = '/app/static/views/feed.mustache'
        self.view.results = self.post.results
        self.view.flags = namedtuple('_', ['x'])('true')
        return self

just imagine the namedtuple was where I loop over the array looking for the x string and I return true or false based on that

现在的问题是,我要编写 namedtuple 代码,我需要知道要循环的结果的哪个 索引。

我是不是漏掉了一些非常明显的东西?

在纯粹基于 Javascript 的 Mustache 模板中,我会这样做:

var results = fetchFromApi();
results['flags_icon'] = function(){
    if ( this == 'x') { return "fa fa-times";/*font awesome icon*/}  
}
var html = Mustache.to_html($("#mytemplate").html(), results);

所以我通过更改代码设计和嵌套 'Presenter' 类 自己设法解决了这个问题(但我很想看看其他人是如何做到的;正如我所尝试的多种其他方法尝试 pystache 语言功能但没有有效的解决方案)...

class Feed(Presenter):
    def prepare_view(self, **params):
        self.view = View()
        self.view.template_path = '/app/static/views/feed.mustache'
        self.view.teasers = self.prepare_teasers()
        return self

    def prepare_teasers(self):
        return [Teaser(Context(result)) for result in self.post.results]

where self.post is set on the Presenter and provides the raw data we're looking to consume

然后 Teaser 与这个顶级 Feed 演示者一样有效地工作,不同之处在于它被赋予了不同的 'context' 对象(即 self.post 值)用作其数据源:

class Teaser(Presenter):
    def prepare_view(self, **params):
        self.view = View()
        self.view.template_path = '/app/static/components/teaser/teaser.mustache'
        self.view.username = self.post.author
        self.view.uri = self.post.uri
        self.view.title = self.post.name
        return self

self.post is now one of the elements from inside self.post.results from the top level Feed presenter

我们的代码从顶级 Presenter (Feed) 开始,并开始递归渲染它找到的每个嵌套 Presenter