错误:
Variable "username" does not exist in HomeHomepageBundle:Template:header.html.twig
at line 27
DefaultController.php
public function indexAction(Request $request)
{
$session = $this->getRequest()->getSession();
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('LoginLoginBundle:Users');
if ($request->getMethod() == 'POST') {
$session->clear();
$username = $request->get('username');
$password = sha1($request->get('password'));
$user = $repository->findOneBy(array(
'username' => $username,
'password' => $password));
if ($user) {
return $this->render('HomeHomepageBundle:Content:Dashboard.html.twig', array(
'username' => $user->getUsername() ,
'password' => $user->getPassword()));
} else {
return $this->render('LoginLoginBundle:Default:index.html.twig', array('username' => 'Username or Password Incorrect'));
$em->persist($user);
$em->flush();
}
} else
return $this->render('LoginLoginBundle:Default:index.html.twig');
header.html.twig
<span data-brackets-id='1813' class="hidden-xs">{{ username }}</span>
我将模板拆分为header.html.twig footer.html.twig leftpanel.html.twig和rightpanel.html.twig并将其包含在default.html.twig中
Index.html.twig
{% include 'HomeHomepageBundle:Template:header.html.twig' %}
{% include 'HomeHomepageBundle:Template:leftpanel.html.twig' %}
</aside>
<div data-bracets-id='1869' class="content-wrapper">
{% block content %}{% endblock %}
<section data-brackets-id='1878' class="content">
</section>
</div>
{% include 'HomeHomepageBundle:Template:footer.html.twig' %}
{% include 'HomeHomepageBundle:Template:rightpanel.html.twig' %}
当我尝试更改{%block content%}时问题开始。在改变内容的同时,在标题上呈现用户名的最佳做法是否有任何想法?
Dashboard.html.twig
{% extends 'HomeHomepageBundle:Default:index.html.twig' %}
{% block content %}
<section data-brackets-id='1870' class="content-header">
<h1 data-brackets-id='1871'>
Greetings! {{ username }}<br>
<small data-brackets-id='1872'>Development in progress</small>
</h1>
<ol data-brackets-id='1873' class="breadcrumb">
<li data-brackets-id='1874'><a data-brackets-id='1875' href="#"><i data-brackets-id='1876' class="fa fa-dashboard"></i>index</a></li>
<li data-brackets-id='1877' class="active">Dashboard</li>
</ol>
</section>
{% endblock %}
{% block javascript %}{% endblock %}
答案 0 :(得分:1)
您应该传递用户名&#39;通过这样做变量到模板:
$this->render('<Template>', ['username' => 'Alex' /* or $username */]);
仔细查看indexAction的最后一行:如果获得请求,则不会传递任何内容。
您可能想要传递用户名&#39; var转换为部分模板,您在index.html.twig中包含该模板。但是,在您没有将其传递到主模板之前,它不会出现在部分模板中。最后的twig版本会自动将传递到主模板的所有变量传递给部分模板 - 因此无需执行此操作。 再一次:控制器中indexAction的最后一行表示当请求方法为GET时,你不会将任何变量传递给模板。
答案 1 :(得分:1)
首先,如果你想在树枝模板中访问用户的名字,丹尼尔的方式就是你的方法。
更通用;您可以将变量传递给包含的模板,如下所示:
{% include 'template.html' with {'foo': 'bar'} %}
有关此主题的更多信息,请阅读文档:http://twig.sensiolabs.org/doc/tags/include.html
答案 2 :(得分:0)
{{ app.user.username }}
。 username
:
{% if username is defined %}{{ username }}{% endif %}
。username
,请在第一个if
声明之前在控制器中定义它。