I’m trying to render some JSON data using jsRender. Below is my sample JSON data
"PageContentList": [
{
"ContentId": 51,
"Title": "60 seconds with Rick",
"ContentMediaTypeList": [
{
"MimeType": "image/png",
"MediaTypeName": "Image",
"Path": "http://local.admin.solutiaconsulting.com/uploads/4a906d8e-983a-4b54-a627-0e8d48145620.png"
},
{
"MimeType": "video/webm",
"MediaTypeName": "Video",
"Path": "http://local.admin.solutiaconsulting.com/uploads/3a6c56c3-0ef9-4f57-9c84-9caa48a09044.webm"
}
]
}
]
I want to pull the different images based on MediaTypeName instead of the ordinal position. I know I can do this:
{{:ContentMediaTypeList[1].Path}}
and I know I can do this:
{{for ContentMediaTypeList}}
{{if MediaTypeName == ‘Video’}}
{{:Path}}
{{/if}}
{{/for}}
But the second approach seems cumbersome and wasteful. Is what I want to do even possible? Thanks for your help.
There is no easy way to do it, because you are not supposed to perform that kind of logic in the view. Place your filter in the model or a controller before you render it.
The one exception I can think of in this case is if you would like to limit the number of items to display. That might or might not be a suitable task for the view depending on the situation.
Examples:
Keep the logic of a limit out of the view:
– List of Question on Stack Overflow with paging (limit, offset, sorting)
Enforce a limit in the view:
– A list of attached images for each question. Your mobile view only have room to show one per question. The view suitable for desktop have room for three.
How to structure your application and where to place your logic is a debate with many opinions though. This style of separation is what I’ve been taught from experience and peers, but I am sure that there are many out there with different idéas.
Here’s a simple way to filter your data using underscore.js.
Working
JSFiddle: http://jsfiddle.net/n98yW/Or create a
closureout of it for reusabilityAnd use it like this
Here’s another
JSFiddlefor this solution using a closure: http://jsfiddle.net/GA55g/2/