The Python Oracle

How to render array of data into multiple mustache partials?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
01:41 Accepted answer (Score 2)
02:58 Answer 2 (Score 0)
03:16 Thank you

--

Full question
https://stackoverflow.com/questions/4047...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #mustache #pystache

#avk47



ACCEPTED ANSWER

Score 2


So I've managed to resolve this issue myself with a change in code design and nesting 'Presenter' classes (but I would be interested to see how others are doing this; as I tried multiple other ways trying pystache language features with no working solution)...

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

The Teaser then works effectively the same as this top level Feed presenter, the difference is it's given a different 'context' object (i.e. self.post value) to use as its data source:

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

Our code starts at the top level presenter (Feed) and starts recursively rendering each nested Presenter it finds




ANSWER 2

Score 0


In pure Javascript based Mustache template I would do this:

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