How to visualize an array of data in several parts of a mustache?

I use Python pystache (which is the standard api utility).

Here is an example of my data structure:

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

Now in my template I am trying to do this:

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

Where stuffis partial and partial looks like this:

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

Now what provides the data to the template is a class that acts as a “presentation model”, so I can normalize some data and have a template that interacts with normalized data, and not with the json source data shown above.

The problem is that I don’t know how to implement my view model to work with the fact that we iterate over nested data.

, flags, , , true false, , x.

:

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

, namedtuple , x, true false

, namedtuple, , .

- ?

+4
2

, "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]

self.post Presenter ,

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 self.post.results Feed

(Feed) Presenter,

+2

Mustache Javascript :

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);
0

Source: https://habr.com/ru/post/1660101/


All Articles