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条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮