【问题标题】:Laravel "{slug}" not being replaced, instead being url encodedLaravel "{slug}" 没有被替换,而是被 url 编码
【发布时间】:2014-10-08 19:14:28
【问题描述】:

我最近开始学习 Laravel。在这样做的过程中,我开始完成网络上的教程,包括来自 youtube。在一个这样的教程中,我一直在开发一个非常基本的博客。在使用蛞蝓时,我遇到了一些僵局。出于某种原因,它只是不想为我工作!

当在我的“routes.php”文件中输入以下代码时,我注意到大括号“{”和“}”会自动转换为 URL 编码并显示“slug”一词。此外,posts 后面的 '/' 无处可见。这意味着链接将读作“http:[域名]/posts/%7Bslug%7D[文章名称]”

Route::get('/posts/{slug}', [
    'as' => 'post-show', 
    'uses' => 'PostController@getIndex'
]);

如果我这样更改代码,问题将部分解决:

Route::get('/posts/{slug?}', [
    'as' => 'post-show', 
    'uses' => 'PostController@getIndex'
]);

“slug”一词不再显示为 URL 的一部分。然而,由于某种原因,蛞蝓前面的“/”仍然不可见,就好像被有问题的蛞蝓吃掉了一样!现在显示为“http:[域名]/posts**%7Bslug%7D**[文章名称]”。

如果有人能伸出援手,我非常感谢您指出正确的方向。谢谢。

【问题讨论】:

  • 欢迎来到 SO。您如何将这些链接插入到您的视图中?一种方法是{{ route('post-show', ['slug' => '123']) }}Other ways are documented online.
  • 感谢主教的快速回复。我使用这种方法将链接插入到我的视图中:@if($posts->count()) @foreach($posts as $post) <article> <h2><a href="{{ URL::action('post-show'), $post->slug }}">{{ $post->title }}</a></h2> {{ Markdown::parse(Str::limit($post->body, 157)) } <a href="{{ URL::action('post-show'), $post->slug }}">read more…</a> </article> @endforeach @endif

标签: php laravel slug


【解决方案1】:

根据您的评论,您调用该操作的方式不正确。试试这个查看代码:

@if ($posts->count())
  @foreach ($posts as $post)
    <article>
      <h2><a href="{{ route('post-show', ['slug' => $post->slug]) }}">{{ $post->title }}</a></h2>  
      {{ Markdown::parse(Str::limit($post->body, 157)) }}
      <a href="{{ route('post-show', ['slug' => $post->slug]) }}">read more&hellip;</a>
    </article>
  @endforeach
@endif

我不在终端附近进行测试,但它应该让你更接近。这段代码解决的问题是:

  1. 要使用路由 name 生成 URL,请使用 route。您的代码使用的是action
  2. 要传递一个参数并填写“{slug}”,您将一个数组作为第二个参数传递给route(以及action)。您的代码既没有传递数组也没有将值传递给函数。
  3. 您在Markdown::parse 之后缺少},但这可能是复制和粘贴错误。

如果这对您有帮助,请记得投票并标记为已接受!

【讨论】:

  • 成功了!是的,至少丢失的} 归结为复制和粘贴错误!奇怪的是,我只是在学习一个教程。原始代码似乎在其中起作用。
猜你喜欢
  • 1970-01-01
  • 2014-08-15
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 2017-11-14
相关资源
最近更新 更多