Ember.js generate html from json with iteration

自闭症网瘾萝莉.ら 提交于 2020-01-06 03:21:47

问题


I'm supposed to use ember.js for a project. I'm converting a json into a HTML view. The json looks something like this:

{
"title": "Some H1 title",
"children": [
    {"title": "Some H2 title",
    "children": .....
    }
]
}

So the result should look like

Some H1 Title

Some H2 Title

Doesn't really matter if it's dynamic with handlebars or static.

What is the recommended emberjs way of doing this? Load the whole json into a data model and go from there? Or just give the object to handlebars? (there is the need for some basic if else logic by the way so the last option might not be the best (e.g. needs more code)).


回答1:


If the data in json has some meaning in the data model of your application, then you should place it in a structure of ember objects and assign them to properties of the controller. If you only need the json data to be displayed and has no meaning in your application's data model, then you can simply assign it directly as a property to the view or controller.

In all cases you will need a handlebars template that will display the data stored in those properties.

For example if you have json data that is composed of objects with a string as title and array of the same objects as children and you want to display all titles of all children regardless of depth you could do something like,

http://emberjs.jsbin.com/UgaVAvIZ/1/edit

hbs

<script type="text/x-handlebars">
    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="index">
    <h1>{{title}}</h1>
    {{partial "childrenPartial"}}
  </script>

  <script type="text/x-handlebars" data-template-name="_childrenPartial">
    {{#each child in children}}
    <h2>{{child.title}}</h2>
    {{#with child.children}}
    {{partial "childrenPartial"}}
    {{/with}}
    {{/each}}
  </script>

js

App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return {"title": "Some H1 title","children": [{"title": "Some H2 title","children": []}]};
  }
});

Please note that using a partial as shown is only one of many other approaches. In this approach the json data has been assigned as model to the specific route and the corresponding view with the help of a partial display the required data.



来源:https://stackoverflow.com/questions/20797738/ember-js-generate-html-from-json-with-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!