Symfony 2 - 访问映射的Object属性表单twig

时间:2012-12-11 10:40:32

标签: symfony doctrine-orm twig

我拥有以下飞行的实体:

/**
 * @ORM\ManyToOne(targetEntity="Document", inversedBy="posts")
 * @ORM\JoinColumn(name="document_id", referencedColumnName="id")
 */
protected $image;

我用以下方法得到:

public function indexAction() {
    $posts = $this->getDoctrine()
            ->getRepository('airpaprcms2Bundle:Post')
            ->findByPageType(1);

    if (!$posts) {
        throw $this->createNotFoundException('No posts in Database!');
    }

    return $this->render('airpaprcms2Bundle:Default:index.html.twig', array('posts' => $posts));
}

如何在树枝中访问映射对象表单的属性?我试过post.image.file(映射的实体Document有一个属性文件)

{% for post in posts %}
<div>
    <h1>
        <a href="{{ path('_view', {'slug': post.slug}) }}">{{ post.title }}</a>
    </h1>
    <p>{{ post.text }}</p>
    <img src="{{ post.image.name }}" alt="{{ post.title }}" />
</div>
{% endfor %}

并收到以下错误消息:

Item "file" for "" does not exist in airpaprcms2Bundle:Default:index.html.twig at line 11

访问映射文档属性的正确语法是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用以下树枝语法访问链接实体的属性:

{% for post in posts %}
{{ post.entityName.propertyName }}
{% endfor %}

在你的情况下:

{% for post in posts %}
{{ post.image.propertyName }}
{% endfor %}

请务必检查所有帖子实体是否已链接到图片对象。如果一个帖子实体没有指向图片的链接,那么在尝试渲染页面时,您将收到找不到属性的错误。