在codeigniter中使用slugs [英] Using slugs in codeigniter

查看:166
本文介绍了在codeigniter中使用slugs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过人们使用lug for来产生干净的网址。我不知道它是如何工作的。
目前我有一个codeigniter网站,生成的URL像这样

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

从我理解的维护一个slug字段可以实现像

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

这是怎么做的?特别是对codeigniter?

How is this done? Especially in reference to codeigniter?

推荐答案

我只是将slugs存储在我的数据库表中,在 slug ,然后找到带有slug的帖子,如下所示:

I just store the slugs in my database table, in a column called slug, then find a post with the slug, like this:

public function view($slug)
{
    $query = $this->db->get_where('posts', array('slug' => $slug), 1);

    // Fetch the post row, display the post view, etc...
}

此外,要轻松从您的帖子标题中导出a,只需使用网址帮助程序的 url_title()

Also, to easily derive a slug from your post title, just use url_title() of the URL helper:

// Use dashes to separate words;
// third param is true to change all letters to lowercase
$slug = url_title($title, 'dash', true);

一点奖励:您可能希望对 slug 列,确保每个帖子都有唯一的lug,所以它不会含糊不清的哪个帖子CodeIgniter应该查找。当然,您应该首先为您的帖子提供唯一的标题,但是这样做会强制实施 该规则,并防止您的应用程序卷入。

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.

这篇关于在codeigniter中使用slugs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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