Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call one of an entity's getter methods from Twig?

Tags:

php

twig

symfony

I have an entity like the below:

class item
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;



/**
 * @ORM\Column(type="integer",nullable=true)
 */


private $errorNum;


public function getErrorNum()
{
    return $this->errorNUm * 3;

}

I can access the $errorNum property in Twig like this after passing the entity to Twig:

{{ item.errorNum }}

However I want to access the getErrorNum() method from Twig.

How can I do it?

like image 852
whitebear Avatar asked Feb 05 '14 14:02

whitebear


1 Answers

You can directly get method in twig:

{{ item.getErrorNum() }}

but if your errorNum property is private, twig himself call the getter of it, so when you use

{{ item.errorNum }}

twig is all the same get getter getErrorNum()

NOTE: For using item in twig you need to pass this object to the template in your action like:

return $this->render("AcmeDemoBundle:Blog:posts.html.twig", array('item' => $item))

where $item is an Item class object

like image 158
Victor Bocharsky Avatar answered Oct 15 '22 11:10

Victor Bocharsky