2014-04-29 45 views
0

當試圖包含其他文件時,我沒有訪問變量。 我嘗試與包括關鍵字添加,但不工作,所有的時間我得到消息:Symfony2包含和訪問變量

變「實體」不 ISLabBundlesBlogBu​​ndle存在:職務:第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 
    )); 
} 

問題是在這個文件中塊側欄。我嘗試包括其他文件,我只提取最後一篇文章。

{% 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> 

我該怎麼辦了?如何解決這個問題?

回答

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(搜索嵌入控制器)