symfony4 - Symfony 4 使用 URL 检查数据库是否存在页面,否则 404
问题描述
我正在尝试构建一个使用尽可能少的模板的论坛,以便使用数据库来填充论坛真正动态。
我想做的是让我的控制器检查数据库并确保 URL 存在。
对象是只有存在的页面才会存在。因此,有人输入地址 host.com/forum/foo/bar 将收到错误消息“ 404 页面不存在”,而不是空白索引模板。
我正在使用 Symfony 4、Docrine、Twig、Annotations 和其他各种插件
当前代码
//src/Controller/Controller.php
/**
* @Route("/forum/{category}/{slug}", name="page_topic")
*/
public function showTopic($slug){
$repository = $this->getDoctrine()->getRepository(Topic::class);
$topic = $repository->findOneBy(['name' => $slug]);
return $this->render('forum/article.html.twig', ['topic' => $topic]);
}
这是主题页面的控制器,它当前循环主题中的所有线程。但是由于在页面加载之前没有检查 {category} 和 {slug},您可以按字面意思输入任何内容并且不会出现错误,只是一个带有空白部分的模板。(我确实尝试过 {topic} 而不是 {slug} 但由于我无法弄清楚如何处理检查,它会给出错误)
//templates/forum/article.html.twig
{% extends 'forum/index.html.twig' %}
{% block forumcore %}
<div id="thread list">
<h4>{{ topic.name }}</h4>
<ul>
{% for thread in topic.childThreads %}
<li><a href="/forum/{{category.name}}/{{ topic.name }}/{{ thread.name }}"><h6>{{ thread.name }}</h6></a></li>
{% endfor %}
</ul>
</div>
{% endblock %}
正如您从 twig 模板中看到的那样,链接依赖于实体的 $name 字段来生成每个页面的 URL,并且是完全动态的。
在此先感谢您,如果您需要更多信息,请在评论中弹出,我可以更新此帖子。
解决方案
为了知道当前是否找到了某个项目,URL
您只需测试是否$topic
是NULL
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* @Route("/forum/{category}/{slug}", name="page_topic")
*/
public function showTopic($slug){
$repository = $this->getDoctrine()->getRepository(Topic::class);
$topic = $repository->findOneBy(['name' => $slug]);
if ($topic === null) throw new NotFoundHttpException('Topic was not found'); // This should activate the 404-page
return $this->render('forum/article.html.twig', ['topic' => $topic]);
}
推荐阅读
- sprite-kit - touchesMoved中的SpriteKit + AVAudioPlayer:杀死fps
- php - 如何在同一个查询中使用多个选择而不弄乱一切
- javascript - 为什么 VS 代码的变量名有问题?
- php - 数据库从 MySQL 迁移到 SQL Server 后 AJAX 不起作用(未定义索引)
- python - Django 没有从 url 参数中获取 id
- javascript - 将数组中的值添加到另一个数组
- javascript - React formik 部分更新初始值
- css - 如何为除了最后一个元素之外的每个元素制作响应方块,它必须与其他元素具有相同的高度?
- node.js - 如何将存储在 POST 中的变量访问到 GET 函数中?
- python - 如何在 Python 中做柯里化函数