在 codeigniter 中使用 slugs
我听说有人使用 slugs 来生成干净的 url。我不知道它是如何工作的。 目前我有一个 codeigniter 网站,它生成这样的 url
www.site.com/index.php/blog/view/7
根据我的理解,通过维护 slug 字段,可以实现像这样的 url
www.site.com/index.php/blog/view/once-upon-a-time
这是如何完成的?特别是关于 codeigniter ?
I have heard of people using slugs for generating clean urls. I have no idea how it works.
Currently i have a codeigniter site which generates url's like this
www.site.com/index.php/blog/view/7
From what i understand by maintaining a slug field it is possible to achieve urls like
www.site.com/index.php/blog/view/once-upon-a-time
How is this done? Especially in reference to codeigniter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只是将 slug 存储在数据库表中名为
slug
的列中,然后找到包含该 slug 的帖子,如下所示:此外,要轻松从帖子标题中导出 slug,只需使用
url_title()
:一点好处:你可以希望对
slug
列实现唯一的键约束,以确保每个帖子都有一个唯一的 slug,这样 CodeIgniter 应该查找哪个帖子就不会含糊不清。当然,您可能应该首先为您的帖子指定独特的标题,但是将其设置到位强制规则并防止您的应用程序搞砸。I just store the slugs in my database table, in a column called
slug
, then find a post with the slug, like this:Also, to easily derive a slug from your post title, just use
url_title()
of the URL helper:A little bonus: you may wish to implement a unique key constraint to the
slug
column, that ensures that each post has a unique slug so it's not ambiguous which post CodeIgniter should look for. Of course, you should probably be giving your posts unique titles in the first place, but putting that in place enforces the rule and prevents your application from screwing up.对于我的 ES 朋友,请使用以下方法从 Text Helper 中删除重音字符:
To my ES friends, remove accented characters using this, from Text Helper:
尝试使用这个包: https://github.com/sawastacks/ci4-slugify
首先,在控制器上导入这个 slugify 类:
你可以得到如下的 slugs:
在更新记录阶段,这样做:
Try to use this package: https://github.com/sawastacks/ci4-slugify
First, import this slugify class on controller:
You can get slugs as follow:
On Updating record stage, do like this: