What is the Symfony2 equivalent of components in Symfony1?
You can create Twig Extension with function widget
and register it in the container. Also inject Kernel
into this extension.
class 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 #}