【问题标题】:Symfony2 include and access to the variablesSymfony2 包含和访问变量
【发布时间】:2014-04-30 02:37:46
【问题描述】:

尝试包含其他文件时,我无法访问变量。 我尝试在 include 中添加关键字但不起作用,我一直收到消息:

变量“实体”不存在于 ISLabBundlesBlogBu​​ndle:Post:last_post.html.twig 在第 6 行

首先我有 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>

我做错了什么?以及如何解决这个问题?

【问题讨论】:

    标签: symfony twig


    【解决方案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(搜索嵌入控制器)

    【讨论】:

      猜你喜欢
      • 2016-03-27
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2021-10-06
      • 2011-12-03
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多