如何使用Yii2可拖拽行为? [英] How to use Yii2 Sluggable Behavior?

查看:168
本文介绍了如何使用Yii2可拖拽行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照文档说明定义了这种行为。

I have defined this behavior as per documentation instructions.

public function behaviors()
{
    return [
        TimestampBehavior::className(),
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
        ],
    ];
}

在我的配置URL管理器中,我定义了如下自定义规则: example.com/article/1

In my config url manager I have defined custom rule like this: 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])

In my index view file I am generating URL to view action like this : Url::to(['article/view', 'id' => $model->id, 'slug' => $model->slug])

我想在url中输出文章标题,如下所示: example.com/article/1/My-first-post

I would like to output my article title in url like this: example.com/article/1/My-first-post

但是我没有在URL中获得标题。

But I am not getting title in URL.

Soju说是一种数据库属性。我已经在文章表中创建了名为slug的新列,它是varchar1024。但是我仍然没有在URL中生成块。我的网址是: example.com/article/1

Soju said that slug is a database attribute. I have created new column in my article table called slug and it is varchar 1024. But I am still not getting slug generated in URL. My URL is: example.com/article/1

怎么了?谢谢

编辑:我已经更新了代码,以将标题值插入到文章表的子句列中。现在,我开始工作了,但没有SEO URL-s。我得到的是: article / 1 / First + Article ,我想要的是 article / 1 / First-Article

EDIT: I have updated my code to insert title value into slug column in my article table. Now I get slug working but I do not get SEO URL-s. I get this: article/1/First+Article, and I would like 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);

推荐答案

您可以添加以下 urlManager 规则:

'article/<id:\d+>/<slug>' => 'article/view',

并在您的视图中构建url,例如:

And build url in your views like this :

\yii\helpers\Url::to(['article/view', 'id'=>$model->id, 'slug'=>$model->slug])

您也可以在您的模型:

public function getRoute()
{
    return ['article/view', 'id'=>$this->id, 'slug'=>$this->slug];
}

public function getUrl()
{
    return \yii\helpers\Url::to($this->getRoute());
}

然后只需使用 $ model-> url 在您的视图中。

And then simply use $model->url in your views.

这篇关于如何使用Yii2可拖拽行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆