Symfony 2 - Access mapped Object property form twi

2019-08-02 18:07发布

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));
}

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

and get the following error message:

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?

1条回答
闹够了就滚
2楼-- · 2019-08-02 19:04

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

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

In your case that would be:

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

查看更多
登录 后发表回答