简体   繁体   English

如何在不显示 ID 号的情况下使用 Yii2 Sluggable Behavior?

[英]How to use Yii2 Sluggable Behavior without showing id number?

I have read the question on using SluggableBehavior in Yii2我已阅读有关在Yii2 中使用 SluggableBehavior的问题

and in my trial case I can generate url like article/1/First-Article using the rule in urlManager在我的试验案例中,我可以使用 urlManager 中的规则生成 url,如 article/1/First-Article

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

and using并使用

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

to create url.创建 url。

In my real case, I use ['article/view', 'hash'=> $model->hash, 'slug'=>$model->slug] to generate url.在我的真实案例中,我使用 ['article/view', 'hash'=> $model->hash, 'slug'=>$model->slug] 来生成 url。 My rule is我的规则是

'article/<hash:[\d-\w]+>/<slug>'=>'article/view'

My url is like article/1e482d69129d760e9494b2c6e86eba2b/First-Article.我的 url 就像文章/1e482d69129d760e9494b2c6e86eba2b/First-Article。

I want to only show url like article/First-Article, ie not showing the hash code in the url.我只想显示 url 之类的文章/首篇文章,即不在 url 中显示 hash 代码。 Is there a way to achieve this?有没有办法做到这一点? Thanks a lot!非常感谢!

According to Yii docs , if your specify SluggableBehavior 's attribute property with an array of model attributes, it will implode (concatenate) them in order to generate uniqueness for the slug.根据Yii docs ,如果您使用 model 属性数组指定SluggableBehaviorattribute属性,它将内爆(连接)它们以生成 slug 的唯一性。 In your case, this implementation perfectly satisfies your desired slug concatenated composition (eg First-Article-1 );在您的情况下,此实现完全满足您所需的 slug 连接组合(例如First-Article-1 );

Internally SluggableBehavior will perform it's generateSlug method to generate unique slug from your attributes composition defined in attribute property.在内部SluggableBehavior将执行它的generateSlug方法,以从属性属性中定义的attribute组合生成唯一的 slug。

Since generateSlug uses - delimiter by default, it perfectly fits your requirements in order to generate desired url slug.由于generateSlug默认使用-分隔符,它完全符合您的要求,以便生成所需的 url slug。

Take a look into this:看看这个:

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

EDIT:编辑:

This is your URL Rule: 'article/<slug>' => 'article/view'这是你的 URL 规则: 'article/<slug>' => 'article/view'

and

Generating appropriate link: Url::to(['article', 'slug' => $model->slug. '-'. $model->id])生成适当的链接: Url::to(['article', 'slug' => $model->slug. '-'. $model->id])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM