In my Symfony2 application, I want to have a widget displayed on various pages. This can't just be defined by its template, it need to call the DB and go through the controller.
In Symfony1, I would create a component and include it. How can I do the same in Symfony2?
Source: Tips4all
I did some more research, and the simplest way I found was just this simple line in the template:
ReplyDelete{% render 'MyBundle:MyController:myAction' %}
This outputs the result of the action, with the template specified by the action.
You can create Twig Extension with function widget and register it in the container. Also inject Kernel into this extension.
ReplyDeleteclass WidgetFactoryExtension extends \Twig_Extension
{
protected $kernel;
public function __construct($kernel)
{
$this->kernel= $kernel;
}
public function getFunctions()
{
return array(
'widget' => new \Twig_Function_Method($this, 'createWidget', array('is_safe' => array('html'))),
);
}
public function createWidget($name, array $options = array())
{
list($bundle, $widget) = explode(':', $name);
$widgetClass = $this->kernel->getBundle($bundle)->getNamespace() . '\\Widget\\' . $widget;
$widgetObj = new $widgetClass();
$widgetObj->setContainer($this->kernel->getContainer());
if ($options) {
$widgetObj->setOptions($options);
}
return $widgetObj;
}
}
And after this write in templates:
{{ widget('QuestionsBundle:LastAnswers', {'answersCount' : 10}) }}
{# class QuestionsBundle/Widget/LastAnswers #}