Symfony1中Symfony2等价的组件是什么?

jih*_*ihi 20 php symfony1 symfony

在我的Symfony2应用程序中,我希望在各个页面上显示一个小部件.这不仅可以通过其模板定义,还需要调用DB并通过控制器.

在Symfony1中,我将创建一个组件并包含它.我如何在Symfony2中做同样的事情?

jih*_*ihi 27

我做了一些更多的研究,我找到的最简单的方法就是模板中的这个简单的一行:

{% render 'MyBundle:MyController:myAction' %}
Run Code Online (Sandbox Code Playgroud)

这将使用操作指定的模板输出操作的结果.

  • 更多信息:http://symfony.com/doc/current/book/templating.html#templating-embedding-controller (4认同)

Koc*_*Koc 8

您可以使用函数创建Twig扩展widget并将其注册到容器中.也注入Kernel此扩展.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在写完模板之后:

{{ widget('QuestionsBundle:LastAnswers', {'answersCount' : 10}) }}
{# class QuestionsBundle/Widget/LastAnswers #}
Run Code Online (Sandbox Code Playgroud)