Emberjs-router-dynamic-segment
提供:Dev Guides
EmberJS-ルーターの動的セグメント
動的セグメントはroute()メソッドの_“:” _で始まり、その後に識別子が続きます。 URLは、モデルのidプロパティで定義されます。
構文
Router.map(function() {
this.route('linkpage', { path: '/linkpage/:identifier' });
});
例
以下の例は、データを表示するために動的セグメントを使用する方法を示しています。 _app/templates/_の下に作成されたファイルを開きます。 ここでは、以下のコードでファイルを_blog-post.hbs_として作成しました-
<h2>My Profile</h2>
Hello
_router.js_ファイルを開いてURLマッピングを定義します-
import Ember from 'ember';
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config
//The const declares read only variable
const Router = Ember.Router.extend ({
location: config.locationType,
rootURL: config.rootURL
});
//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
this.route('blog-post', { path: '/blog-post/:username'});
});
export default Router;
_application.hbs_ファイルを作成し、次のコードを追加します-
{{#link-to 'blog-post' 'smith'}}View Profile{{/link-to}}
{{outlet}}
URLを構築するには、モデルを渡し、動的セグメントをキーとしてオブジェクトを返すserializeフックを実装する必要があります。
import Ember from 'ember';
export default Ember.Route.extend ({
model: function(params, transition) {
return { username: params.username };
},
serialize: function(model) {
return { username: model.get('username') };
}
});
出力
エンバーサーバーを実行すると、以下の出力が得られます-
出力のリンクをクリックすると、URLルートが_nestedroute/fruits_として表示され、_fruits.hbs_からの結果が表示されます-