CakePHP: Use post title as the slug for view method

戏子无情 提交于 2020-01-20 09:01:32

问题


I have been trying to do the following method to create urls like:

domain.com/portfolio/This_is_a_test_post

function view ( $title )
{       
    $post = $this->Portfolio->find('first', array('conditions' => array(Inflector::slug('Portfolio.title') => $title)));

    //$posts = $this->Portfolio->title = Inflector::slug($title);

    if (empty($title))
    {
        $this->cakeError('error404');
    }
    else
    {
        $this->set(compact('post'));
    }
}

However it doesn't show the post! Obviously I'm doing something wrong... Any ideas on how I could fix this? Thanks


回答1:


I would recommend using the ID for addressing content on your website, this way you do not have to worry about dealing with title/slug changes. For a SEO perspective you can easily use the Slug without doing anything with it technically:

function view($id) {
   $this->Post->id = $id;
   $this->set('post',$this->Post->read());
}

And in your view, create links like this:

$this->Html->link('name of the link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id'], Inflector::slug($post['Post']['title'])));

Now your URL's will look like this:

domain.com/posts/13/This_is_a_test_post

Note that the slug isn't doing anything, but is giving you the benefit of SEO




回答2:


It does not work because you are applying the Inflector::slug function to the name of the column.. Try the other way around.., add a slug column to your post, and create the slug when you add the post using the Inflector, try something like this when you add your post:

$this->data['Post']['slug'] = Inflector::slug($this->data['Post']['title']);

and on your controller, do this:

function view($slug = null) {
    if (is_null($slug)) {
        $this->cakeError('error404');
    } else {
        $post = $this->Post->findBySlug($slug);
        $this->set(compact('post'));
    }
}

that should do the trick.. i hope it helps..




回答3:


you can't do that. When saving the post, you should slug the title already; or if you want to keep the title, put the slug to another field to find later.

 function view ( $title = null ){       
   if(!$title)$this->redirect(array('action'=>'index'));
   $post = $this->Portfolio->find('first', array('conditions' => array('Portfolio.title' => $title)));
   $this->set(compact('post'));
 }



回答4:


you can use this lib support to convert urls without more efforts

http://someguyjeremy.com/blog/slugs-ugly-bugs-pretty-urls



来源:https://stackoverflow.com/questions/7033710/cakephp-use-post-title-as-the-slug-for-view-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!