如何使用 iron router 包在 Meteor 应用程序中动态设置路由器选项?
How can I dynamically set router options in a Meteor application using the iron router package?
我想将路由选项标签设置为当前url的标签,例如
Router.route('/:_url', {
label: '_url',
action: function () {
this.render('home');
}
});
这是我的帮手:
if (Meteor.isClient) {
Template.home.helpers({
getLabel: function() {
return Router.current().route.options.label;
}
});
}
这是我的模板:
<template name="home">
hi
{{getLabel}}
</template>
当我访问 locolhost:3000/alexander
时,我应该看到 hi alexander
但是我看到 hi _url
如何让 _url 变量正确解析以便我看到 hi alexander
?
您可以设置路由的数据上下文以包含 URL 参数,如下所示:
JS
Router.route("/:name", {
name: "home",
template: "home",
data: function(){
return {
label: this.params.name
};
}
});
HTML
<template name="home">
<h3>Hi {{label}}</h3>
</template>
Router.route("/:name", {
name: "home",
template: "home",
data: function(){
// this will create a new key myName on the route object for this route
// and set the value to the name that the user entered in the path
this.route.options.myName = this.params.name;
return {
label: this.params.name
};
}
});
// All routes are stored in the Router.routes array
// Loop through it to find the only one with a myName key and return the value
for (var i = 0; i < Router.routes.length; i++){
if (Router.routes[i].options.myName){
console.log(Router.routes[i].options.myName);
}
}
我想将路由选项标签设置为当前url的标签,例如
Router.route('/:_url', {
label: '_url',
action: function () {
this.render('home');
}
});
这是我的帮手:
if (Meteor.isClient) {
Template.home.helpers({
getLabel: function() {
return Router.current().route.options.label;
}
});
}
这是我的模板:
<template name="home">
hi
{{getLabel}}
</template>
当我访问 locolhost:3000/alexander
时,我应该看到 hi alexander
但是我看到 hi _url
如何让 _url 变量正确解析以便我看到 hi alexander
?
您可以设置路由的数据上下文以包含 URL 参数,如下所示:
JS
Router.route("/:name", {
name: "home",
template: "home",
data: function(){
return {
label: this.params.name
};
}
});
HTML
<template name="home">
<h3>Hi {{label}}</h3>
</template>
Router.route("/:name", {
name: "home",
template: "home",
data: function(){
// this will create a new key myName on the route object for this route
// and set the value to the name that the user entered in the path
this.route.options.myName = this.params.name;
return {
label: this.params.name
};
}
});
// All routes are stored in the Router.routes array
// Loop through it to find the only one with a myName key and return the value
for (var i = 0; i < Router.routes.length; i++){
if (Router.routes[i].options.myName){
console.log(Router.routes[i].options.myName);
}
}