hassen zouari hassen zouari - 3 months ago 14
PHP Question

Passing parameters to Twig extension from template?

I use Twig extension to pass global variables from the database like in the code below. But I want to make this more dynamic to get data from database by the

id
parameter ..

service

app.twig.database_globals_extension:
class: Coursat\CoursatBundle\Twig\Extension\DatabaseGlobalsExtension
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: twig.extension }


extension

<?php

namespace Coursat\CoursatBundle\Twig\Extension;

use Doctrine\ORM\EntityManager;

class DatabaseGlobalsExtension extends \Twig_Extension
{

protected $em;

public function __construct(EntityManager $em)
{
$this->em = $em;
}

public function getGlobals()
{
return array (
"myVariable" => $this->em->getRepository('CoursatBundle:test')->find(##I want to pass a var here from the template##),
);
}

public function getName()
{
return "CoursatBundle:DatabaseGlobalsExtension";
}

}


template

{{ myVariable.name() }}

Answer

This is a very bad idea to store this in your globals, because your database will be requested for each calls of your website.

You can use a function to retrieve those data:

<?php

namespace Coursat\CoursatBundle\Twig\Extension;

use Doctrine\ORM\EntityManager;

class DatabaseGlobalsExtension extends \Twig_Extension
{

   protected $em;

   public function __construct(EntityManager $em)
   {
      $this->em = $em;
   }

   public function getFunctions()
   {
        return array(
            new \Twig_SimpleFunction('my_test', array($this, 'myTest')),
        );
   }

   public function myTest($id)
   {
      return $this->em->getRepository('CoursatBundle:test')->find($id);
   }

   public function getName()
   {
      return "CoursatBundle:DatabaseGlobalsExtension";
   }

}

Then in your Twig template, use this to load your entity:

{% set twigVar = my_test(42) %}

This is still a bad practice though, you should load your entities in your controllers, not in your views.