尝试包含其他文件时,我无法访问变量。 我尝试在include中添加关键字但不工作,所有时间我收到消息:
变量"实体"在...中不存在 ISLabBundlesBlogBundle:帖子:第6行的last_post.html.twig
首先我有indexAction(),其中列出了所有已发布的博文。
public function indexAction()
{
$posts = $this->getDoctrine()->getRepository('ISLabBundlesBlogBundle:Post')->getAllPublishedPosts();
return $this->render('ISLabBundlesBlogBundle:Page:index.html.twig', array(
'posts' => $posts
));
}
并且有列表只发布最后发布的方法
public function lastPostAction($count = 1)
{
$entity = $this->getDoctrine()->getRepository('ISLabBundlesBlogBundle:Post')->getLastPosts($count);
return $this->render('ISLabBundlesBlogBundle:Post:last_post.html.twig', array(
'entity' => $entity
));
}
问题出在块边栏中的此文件中。我尝试包含其他文件,我最后只获取1个帖子。
{% extends 'ISLabBundlesBlogBundle::layout.html.twig' %}
{% block body %}
{# Fetch all post#}
{% if posts %}
{% for post in posts %}
<article class="blog">
<div class="date"><time datetime="{{ post.created|date('c') }}">{{ post.created|date('l, F j, Y') }}</time></div>
<header><h2> {{ post.title }} </h2></header>
<p> {{ post.body }} </p>
</article>
{% endfor %}
{% endif %}
{% endblock %}
{% block sidebar %}
{% include 'ISLabBundlesBlogBundle:Post:last_post.html.twig'%}
{% endblock %}
这是我尝试包含的文件:
<h2>Last Posts</h2>
<div class="blog">
<ul>
{% for item in entity %}
<li><a href="">{{item.title}}</a></li>
{% endfor %}
</ul>
</div>
我做错了什么?以及如何解决这个问题?
答案 0 :(得分:1)
您需要将实体传递给索引模板:
public function indexAction()
{
$posts = $this->getDoctrine()->getRepository('ISLabBundlesBlogBundle:Post')->getAllPublishedPosts();
$entity = $this->getDoctrine()->getRepository('ISLabBundlesBlogBundle:Post')->getLastPosts(1);
return $this->render('ISLabBundlesBlogBundle:Page:index.html.twig', array(
'posts' => $posts,
'entity' => $entity,
));
}
使用嵌入式控制器也可以(也可能更好):
{% block sidebar %}
{{ render(controller('ISLabBundlesBlogBundle:Post:lastPost', {
'count': 1
})) }}
{% endblock %}
http://symfony.com/doc/current/book/templating.html(搜索嵌入控制器)