CakePHP: Use post title as the slug for view method

后端 未结 4 687
情深已故
情深已故 2020-12-22 06:44

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

domain.com/portfolio/This_is_a_test_post

function view ( $title )
{           


        
4条回答
  •  生来不讨喜
    2020-12-22 07:30

    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..

提交回复
热议问题