如何使用 Meteor 中的 Iron Router 将自定义 ID 分配给动态生成的 URL?
How do I assign a custom ID to a dynamically generated URL with Iron Router in Meteor?
如何让动态生成的 post 的 URL 成为分配给它的属性之一?说出它的名字?所以 events/vbMmmw6ymrWXjtXPd 而不是 URL 是 events/name-of-the-event
到目前为止,这是我的路线:
Router.route('/events/:_id', {
name: 'event',
data: function() { return Events.findOne(this.params._id);}
});
我的架构:
Events = new Mongo.Collection("events");
Events.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Name",
max: 200
},
crew: {
type: String,
label: "Crew"
},
location: {
type: String,
label: "Location"
},
date: {
type: Date,
label: "Date"
},
description: {
type: String,
label: "Wha'appening?",
max: 1000
}
}));
您应该在您的架构中添加独特的 slug(基于名称),例如:
Events.attachSchema(new SimpleSchema({
slug: { //example: my-name-slug
type: String
},
(...)
}));
然后在您的路由器中:
Router.route('/events/:slug', {
name: 'event',
data: function() { return Events.findOne({slug: this.params.slug});}
});
你可以试试这样的东西:
var makeSlug = function (str) {
str = str.toLowerCase();
str = str.replace(/[^a-z0-9]+/g, '-');
str = str.replace(/^-|-$/g, '');
return str;
}
Events.attachSchema(new SimpleSchema({
slug: { //example: my-name-slug
type: String,
autoValue: function() {
if (this.isInsert) {
return makeSlug(this.field('name'));
} else if (this.isUpsert) {
return {$setOnInsert: makeSlug(this.field('name'))};
} else {
this.unset();
}
}
},
(...)
}));
请注意,这未经测试;) 请记住,如果您更新名称,则 slug 不应更新。这里被屏蔽了。
如何让动态生成的 post 的 URL 成为分配给它的属性之一?说出它的名字?所以 events/vbMmmw6ymrWXjtXPd 而不是 URL 是 events/name-of-the-event
到目前为止,这是我的路线:
Router.route('/events/:_id', {
name: 'event',
data: function() { return Events.findOne(this.params._id);}
});
我的架构:
Events = new Mongo.Collection("events");
Events.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Name",
max: 200
},
crew: {
type: String,
label: "Crew"
},
location: {
type: String,
label: "Location"
},
date: {
type: Date,
label: "Date"
},
description: {
type: String,
label: "Wha'appening?",
max: 1000
}
}));
您应该在您的架构中添加独特的 slug(基于名称),例如:
Events.attachSchema(new SimpleSchema({
slug: { //example: my-name-slug
type: String
},
(...)
}));
然后在您的路由器中:
Router.route('/events/:slug', {
name: 'event',
data: function() { return Events.findOne({slug: this.params.slug});}
});
你可以试试这样的东西:
var makeSlug = function (str) {
str = str.toLowerCase();
str = str.replace(/[^a-z0-9]+/g, '-');
str = str.replace(/^-|-$/g, '');
return str;
}
Events.attachSchema(new SimpleSchema({
slug: { //example: my-name-slug
type: String,
autoValue: function() {
if (this.isInsert) {
return makeSlug(this.field('name'));
} else if (this.isUpsert) {
return {$setOnInsert: makeSlug(this.field('name'))};
} else {
this.unset();
}
}
},
(...)
}));
请注意,这未经测试;) 请记住,如果您更新名称,则 slug 不应更新。这里被屏蔽了。