duansengcha9114 2016-05-13 19:30
浏览 64
已采纳

在Slim中,如何传递GET变量进行渲染

I've only been working with Slim for a short while. I'm still on version 2. So far everything has been going just fine, but I've hit a little snag. I have a page that displays content based on a GET variable at the end of the URL. The url looks like the following...

http://localhost/trailcache.com/checklist/21

The first line of the get route looks like this...

$app->get('/checklist/:Id', function($Id) use($app) {

It ends like this...

})->name('checklist');

That Id parameter controls what info I'm pulling into the page and everything has been going just fine, but now I've added a contact form and with it, some validation. I'm writing to the DB and rendering the new content okay. The problem arises when I try to send errors back to the page. Currently it looks like this...

$app->render('user/checklist.php', [
    'Id' => $Id,
    'errors' => $v->errors(),
    'request' => $request
])->name('checklist');

This doesn't work. The page is blank. The url it returns is...

http://localhost/trailcache.com/checklist

The documentation for render shows...

$app->get('/books/:id', function ($id) use ($app) {
    $app->render('myTemplate.php', array('id' => $id));
});

Wouldn't that work in the post route the same way? It has on all my other pages.

How can it get pass those errors along with the correct GET variable so that the correct content displays?

  • 写回答

2条回答 默认 最新

  • dqn8235 2016-05-19 16:10
    关注

    After a few days of struggling with this, I found a solution. I first discovered map() and changed the first line to...

    $app->map('/checklist/:Id', function($Id) use($app) {
    

    and the end to...

    })->via('GET', 'POST')->name('checklist');
    

    so now the route renders the same whether it's coming from post or get. I then pointed the form to this named route...

    <form action="{{ urlFor('checklist', {Id: Id}) }}" class="form" method="post">
    

    and moved all the post logic inside this route. Since there is no need to validate if the request wasn't a post I used...

    if($app->request->isPost()) {
    

    and put the validation code inside. Refreshing the page after making a form submission would resubmit the form so if validation passed I added...

    return $app->response->redirect($app->urlFor('checklist', array(
                'Id' => $Id
            )));
    

    All I had to do was pass the errors to the template and it seems to be working perfectly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站