Twig无法识别传递给模板的变量

Twig无法识别传递给模板的变量

问题描述:

I'm trying to render several things on the page at once (latest articles, newest events, ...). I'm using Symfony2 with Doctrine2.

This is what my controller code looks like:

  public function indexAction()
  {
    $em = $this->getDoctrine()->getManager();

    $articles = $this->getDoctrine()->getRepository('MyAppBundle:Article')->findOrderedByDate(3);
    $events = $this->getDoctrine()->getRepository('MyAppBundle:Event')->findOrderedByDate(2);


    \Doctrine\Common\Util\Debug::dump($events);

    return $this->render('MyAppBundle:Page:index.html.twig', array(
      'articles' => $articles,
      'events', $events
    ));
  }

The dump of the events reveals that it's a StdArray with one item in it (the event from my database). However, if I try to visit the page I get the following Symfony2 error:

Variable "events" does not exist in MyAppBundle:Page:index.html.twig at line 47

The relevant Twig template part is as follows (it's the exact same as the articles):

{% for event in events %}
  <h2>{{ event.name }}</h2>
  <p class="small">{{ event.eventdate|date('Y-m-d H:i:s') }}</p>
  <p>{{ event.intro }} <a href="#">Lees meer &raquo;</a></p>
  <hr class="dotted">
{% endfor %}

It seems to me that variables aren't being passed into the view properly, since I can't even display a hardcoded string (i.e. 'fruit', 'banana').

Has anyone got a clue as to why this is happening?

我正在尝试一次在页面上呈现多个内容(最新文章,最新事件......) 。 我正在使用Symfony2和Doctrine2。 p>

这就是我的控制器代码: p>

  public function indexAction()
 {  
 $ em = $ this-&gt; getDoctrine() - &gt; getManager(); 
 
 $ articles = $ this-&gt; getDoctrine() - &gt; getRepository('MyAppBundle:Article') - &gt; findOrderedByDate  (3); 
 $ events = $ this-&gt; getDoctrine() - &gt; getRepository('MyAppBundle:Event') - &gt; findOrderedByDate(2); 
 
 
 \ Doctrine \ Common \ Util \ Debug  :: dump($ events); 
 
返回$ this-&gt; render('MyAppBundle:Page:index.html.twig',数组(
'articles'=&gt; $ articles,
'events'  ,$ events 
)); 
} 
  code>  pre> 
 
 

事件的转储显示它是一个StdArray,其中包含一个项目(来自我的数据库的事件) 。 但是,如果我尝试访问该页面,我会收到以下Symfony2错误: p>

  MyAppBundle中不存在变量“events”:第47行的Page:index.html.twig  
  code>  pre> 
 
 

相关的Twig模板部分如下(它与文章完全相同): p>

  { 事件中事件的百分比%} 
&lt; h2&gt; {{event.name}}&lt; / h2&gt; 
&lt; p class =“small”&gt; {{event.eventdate | date('Ymd H:i  :s')}}&lt; / p&gt; 
&lt; p&gt; {{event.intro}}&lt; a href =“#”&gt; Lees meer&amp; raquo;&lt; / a&gt;&lt; / p&gt;  
&lt; hr class =“dotted”&gt; 
 {%endfor%} 
  code>  pre> 
 
 

在我看来,变量没有被传递到视图中 正确的,因为我甚至无法显示硬编码的字符串(即'水果','香蕉')。 p>

有没有人知道为什么会发生这种情况? p> div>

'events', $events should be changed to 'events' => $events