Symfony 2-访问树枝对象映射的对象属性 [英] Symfony 2 - Access mapped Object property form twig

查看:77
本文介绍了Symfony 2-访问树枝对象映射的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体,有以下文件:

I hava a entity with the following flied:

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

我可以通过以下方法获得:

which I get with the following method:

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 (映射的实体文档具有属性文件)

How can I access a property of the mapped object form within twig? I tried post.image.file (the mapped entity Document has a property file)

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

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

What is the right syntax to access the mapped document property?

推荐答案

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

You can access the property of your linked entity with the following twig syntax:

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

在您的情况下,将是:

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

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

Be sure to check that all post entities are linked to an image object. If one post entity has no link to an image, you will get a property not found error when trying to render your page.

这篇关于Symfony 2-访问树枝对象映射的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆