cakephp url修改:删除操作并添加slug inflector [英] cakephp url modification: remove action and add slug inflector

查看:217
本文介绍了cakephp url修改:删除操作并添加slug inflector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图删除cakephp url中的操作,并添加一个slug inflector,更清楚这是我的预期输出:

从这里:example.com/posts/view/81 /这是一个测试post

到这里:example.com/posts/This-is-a-test-post

I'm trying to remove the action in the cakephp url and add a slug inflector, to be more clear this is my expected output:
from this: example.com/posts/view/81/This is a test post
to this: example.com/posts/This-is-a-test-post

这是我当前的代码:

这给我这个输出:example.com/posts/view/This是一个测试帖子

控制器:

public function view($title = null) {
        if (!$title) {
            throw new NotFoundException(__('Invalid post'));
        }
        $post = $this->Post->findByTitle($title);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('post', $post);
    }

view.ctp:

$this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['title']));

我也试过这个,这个链接是我的参考 CakePHP:使用帖子标题作为视图方法的method子

输出:example.com/posts/view/21/This-is-a-test-post

I also tried this one,this link being my reference CakePHP: Use post title as the slug for view method :
Output: example.com/posts/view/21/This-is-a-test-post

控制器:

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

view.ctp

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

是我尝试但失败的其他链接,我也尝试修改routes.php,但无法使正确的代码使其工作

below are the other links that I tried but failed, I also tried the modifying the routes.php but can't make the proper code to make it work

想从URL中删除操作名称CakePHP

如何从cakephp中的url中删除操作名称?

在cakephp中从网址中移除操作名称?

任何帮助/建议非常感谢。

any help/suggestions is appreciated thanks.

推荐答案

使用ID和命名参数...

Use Id and Named parameter...

上定义新路线为 -

define new routes as-

Router::connect('/posts/:id-:title',
    array('controller' => 'posts',
        'action' => 'view')
);

这个新定义的路由将匹配和解析包含id和title的所有url命名为parameter ..

This new defined routes will match and parse all url containing id and title named parameter..

重要注意:: 不要在routes.php结束后定义新路线。尝试在文件的中间定义。

Important Note:: Do not define new routes after the end of routes.php. Try to define on the middle of the file..

echo $this->Html->link('Hi',array(
    'controller' => 'posts',
    'action' => 'view',
    'id' => 4,
    'title' => Inflector::slug('the quick brown fox')
));

这篇关于cakephp url修改:删除操作并添加slug inflector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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