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

13,090

Solution 1

Firstly you should change your property private errorNum to protected errorNum and then from your controller return:

return $this->render("AcmeDemoBundle:Product:create.html.twig", array('item' => $item));

Then in your twig view , you can access property:

{{item.errorNum}}

You can also access method :

{{item.ErrorNum}}

Solution 2

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

Share:
13,090
whitebear
Author by

whitebear

Updated on June 21, 2022

Comments

  • whitebear
    whitebear almost 2 years

    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?