ayala
ayala

Reputation: 37

EmberJS 2 Dynamic Routing

I'm trying to setup a way to define routes, their template and model dynamically. (Ember 2.16.0)

So far I have this:

// app/router.js
Router.map(function () {

    let routes = [
        {route: "page_one", templateName: "default.hbs"},
        {route: "page_two", templateName: "default.hbs"},
        {route: "page_three", templateName: "custom.hbs"}
    ];

    routes.forEach(function (key) {
        this.route(key.route);
    }, this);
});

This works, and allows me to load pages if their template file exists.

I want to take this a step further and define the template name here, for example I want them all to use "default.hbs" as well as load the model for them dynamically.

Is this something that's possible in EmberJS? If so which documentation should I be looking at to do so.

I'm aware you can specify templates in their corresponding route file "app/routes/page_one.js" but this wouldn't be dynamic.

Upvotes: 0

Views: 738

Answers (1)

acorncom
acorncom

Reputation: 5955

By default, Ember's approach to routing and templates is to use built-in templates that handle layout of data that comes from a backend. It's perfectly possible do something like this however and end up with your CMS pages being displayed at /page/:slug:

// app/router.js

Router.map(function () {
  this.route('page', { path: '/:post_id' });
});

Doing the above would then allow you to set your page route to handle retrieving the appropriate data from your CMS and then display it in your page.hbs (with the option to wrap it with any additional HTML to make it work well in Ember).

Here's one example of an Ember add-on that does something like that. https://github.com/oskarrough/ember-wordpress It also has a working test app that is designed to work against a Wordpress backend that you can study here: https://github.com/oskarrough/ember-wordpress/tree/master/tests/dummy

There are other approaches you could take as well, but this is probably the simplest one. Does that help?

Upvotes: 1

Related Questions