我创建了一个自定义错误模板
app/Resources/TwigBundle/views/Exception/error404.html.twig
和
app/Resources/TwigBundle/views/Exception/exception_full.html.twig
用于开发将布局更改为我想要的。这很好用。但是,一旦我使用
添加表单(例如我的搜索或联系表单){{ include ('MyCoreBundle:Default/forms:myCustomForm.html.twig') }}
或者直接输入代码,它会显示 ResourceNotFoundException
和 NotFoundHttpException
而不是 404 页面。
有什么方法可以在错误模板上显示表单吗?
最佳答案
使用 embedded controller 怎么样? ?
这是取自 Symfony 文档页面的简短示例。
您有一个返回并呈现一些输出的 Controller :
// src/Acme/ArticleBundle/Controller/ArticleController.php
class ArticleController extends Controller
{
public function recentArticlesAction($max = 3)
{
// make a database call or other logic
// to get the "$max" most recent articles
$articles = ...;
return $this->render(
'AcmeArticleBundle:Article:recentList.html.twig',
array('articles' => $articles)
);
}
}
在此示例中,它呈现一个 View :
{# src/Acme/ArticleBundle/Resources/views/Article/recentList.html.twig #}
{% for article in articles %}
<a href="/article/{{ article.slug }}">
{{ article.title }}
</a>
{% endfor %}
并在您想要嵌入 Controller 操作的 View 中:
{# app/Resources/views/base.html.twig #}
{# ... #}
<div id="sidebar">
{{ render(controller('AcmeArticleBundle:Article:recentArticles', {
'max': 3
})) }}
</div>
文档页面还指出,当您需要模板中无法访问的数据时,应该使用嵌入式 Controller 。从我的角度来看,它非常适合创建小部件、一些统计数据等。
希望这有帮助。
编辑
为了使这个答案更准确地解决您的问题,这是我使用的解决方案:
- 您需要一个 Controller ,我们将其命名为
SearchController
- 在 Controller 的
renderForm()
方法中,您需要创建一个表单并将其传递给 View - 表单的 action 属性应指向
resultAction()
方法,您可以在其中从数据存储中获取结果并向最终用户显示结果。
关于forms - Symfony2 在错误页面上包含表单(404),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21497373/