How to render array of data into multiple mustache partials?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 How To Render Array Of Data Into Multiple Mustache Partials?
01:30 Answer 1 Score 0
01:44 Accepted Answer Score 2
02:47 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.postis set on thePresenterand 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.postis now one of the elements from insideself.post.resultsfrom the top levelFeedpresenter
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);