【发布时间】:2015-05-04 13:18:16
【问题描述】:
我已根据文档说明定义了此行为。
public function behaviors()
{
return [
TimestampBehavior::className(),
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
],
];
}
在我的配置 url 管理器中,我定义了这样的自定义规则:example.com/article/1
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'article/<id:\d+>/<slug>' => 'article/view',
],
],
我的视图操作是:
public function actionView($id, $slug = null)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
在我的索引视图文件中,我正在生成 URL 以查看如下操作:Url::to(['article/view', 'id' => $model->id, 'slug' => $model->slug])
我想在 url 中输出我的文章标题,如下所示:example.com/article/1/My-first-post
但我没有在 URL 中获得标题。
Soju 说 slug 是一个数据库属性。我在我的文章表中创建了名为 slug 的新列,它是 varchar 1024。但我仍然没有在 URL 中生成 slug。我的网址是:example.com/article/1
怎么了?谢谢
编辑:我更新了代码,将标题值插入到文章表的 slug 列中。现在我得到了 slug 的工作,但我没有得到 SEO URL-s。我知道了:article/1/First+Article,我想要article/1/First-Article。
我试过了:
return [
TimestampBehavior::className(),
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
'value' => function ($event) {
return str_replace(' ', '-', $this->slug);
}
],
];
这也不起作用:return str_replace(' ', '-', $this->slug);
【问题讨论】: