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

Cap*_*ppY 5 widget symfony

假设我在网站上的多个地方都有评论.我怎样才能创建像{{render_widget('comments',{"object":object})}}这样的东西?这会使表单和列表包含该对象的所有注释吗?

Vic*_*sky 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...
    }
}
Run Code Online (Sandbox Code Playgroud)

申报服务:

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

在控制器中使用服务:

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

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

#AcmeHelloBundle:Blog:index.html.twig

{{ widget.getComments()|raw }}
Run Code Online (Sandbox Code Playgroud)

阅读有关如何使用范围的文档非常有用