1

我有一个具有以下飞行的实体:

/**
 * @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));
}

如何访问 twig 中映射对象表单的属性?我试过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

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

4

1 回答 1

3

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

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

在你的情况下,这将是:

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

请务必检查所有帖子实体是否都链接到图像对象。如果一个帖子实体没有指向图像的链接,则在尝试呈现页面时将收到属性未找到错误。

于 2012-12-11T19:35:51.867 回答