Patrick Kenekayoro Patrick Kenekayoro - 3 months ago 16
Twig Question

Call function with parameters from Twig

Apologies if this has already been asked. I've done some searching and not found a simple solution.

I have a symfony/doctrine project. What is the appropriate way to call a function from twig given that the business logic should not be placed in the view.

I have an array of objects and I would like to check if the logged in user is the owner of each object in the post.

For example is this appropriate

//in twig template
{% for post in posts %}
{% if post.isOwner(user_id) %}
//do stuff
{% endif %}
{% endfor %}


and in the post entity have this

//in entity
public function isOwner(user_id){
if (post.getId() == user_id)
return true;
return false
}


If this isn't best practice, how can this be achieved appropriately.

VaN VaN
Answer

Dont know what u're attempting to do, but if you want to loop through a specific user posts, you'd rather build a bi-directionnal relations and loop on posts using

{% for post in app.user.posts %}

In the other hand, if you want to loop through all the posts and do some custom logic for posts owned by authed user, you're good to go with your original code. I would change some things though :

For semantic/readability reasons, I would change

//in twig template
{% for post in posts %}
    {% if  post.isOwner(user_id) %}
        //do stuff
    {% endif %}
{% endfor %}

to

//in twig template
{% for post in posts %}
    {% if  app.user.isOwner(post) %}
        //do stuff
    {% endif %}
{% endfor %}

or

{% for post in posts %}
    {% if  post.isOwnedBy(app.user) %}
        //do stuff
    {% endif %}
{% endfor %}

And I would correct the logic method :

//in entity AcmeBundle\User    
public function isOwner(AcmeBundle\Post $post){
    if ($this == $post->getUser()) {
        return true;
    }

    return false;
}