Reputation: 27638
I have a voting system in a Symfony application and I'm using the Twig Engine. I want to be able to do something like this within my template to show the user they've already voted (think StackOverflow orange arrows).
<div class="vote {% if entry.votes.user == loggedinuser %}already-voted{% endif %}">Vote</a>
The problem with this is though, each entry can have multiple votes (so votes
is actually a PersistentCollection
. I know I could do this with PHP or even by looping through each of the votes.user
, but thats messy).
Upvotes: 1
Views: 813
Reputation: 409
You could add a method to your entity so that your template would remain clean and the business logic would be tucked away in the entity similar to:
<div class="vote {% if entry.hasVoted(loggedinuser) %}already-voted{% endif %}">Vote</a>
Upvotes: 1
Reputation: 5280
You can use the in operator instead of iterating over each vote instance. According to Twig documentation the in filter will perform a containment test on strings, arrays, or objects implementing the Traversable interface.
Try the following:
<div class="vote {% if loggedinuser in entry.votes.user %}already-voted{% endif %}">Vote</a>
EDIT:
It seems like the in operator doesn´t work with an instance inside a Collection. I'm afraid you will need to iterate over each vote to check whether both users match or not.
In order to prevent things getting messy you could use a macro.
Hope it helps.
Upvotes: 0