Symfony如何使用PHP和twig创建可重用的小部件

时间:2014-01-20 19:25:45

标签: symfony widget

假设我在网站上有多个评论。我怎样才能创造类似的东西 {{render_widget('comments',{“object”:object})}}?这会使表单和列表包含该对象的所有注释吗?

2 个答案:

答案 0 :(得分:5)

创建服务:

// src/Acme/HelloBundle/Service/Widget.php
namespace Acme\HelloBundle\Service;

use Symfony\Component\DependencyInjection\ContainerInterface;

class Widget
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getComments()
    {
        $request = $this->container->get('request'); // use service_container to access request, doctrine, twig, etc...
    }
}

宣布服务:

# src/Acme/HelloBundle/Resources/config/services.yml
parameters:
    # ...
    my_widget.class: Acme\HelloBundle\Service\Widget

services:
    my_widget:
        class:     "%my_widget.class%"
        arguments: ["@service_container"]
        # scope: container can be omitted as it is the default

在控制器中使用服务:

namespace Acme\HelloBundle\Controller;

class BlogController {

    public function getPostAction($id) {
        // get post from db
        $widget = $this->get('my_widget'); // get your widget in controller
        $comments = $widget->getComments(); // do something with comments

        return $this->render('AcmeHelloBundle:Blog:index.html.twig',
            array('widget' => $widget) // pass widget to twig
        );
    }
}

或在树枝中,如果您在render()函数中的上述模板中传递服务:

#AcmeHelloBundle:Blog:index.html.twig

{{ widget.getComments()|raw }}

阅读有关How to work with Scopes

的文档非常有用

答案 1 :(得分:1)

我以另一种方式做到了。我使用函数{{comments(object)}}

注册了Twig Extension

该功能以

方式注册
'comments' => new \Twig_Function_Method($this, 'comments', array(
        'needs_environment' => true,
        'is_safe' => array('html')
            ))

这样我就不需要指定| raw filter。