Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony how to create reusable widget with PHP and twig

Tags:

widget

symfony

Let's say I have comments in more than one spot in website. How can I create something like {{ render_widget('comments', {"object": object} ) }} ? That would render the form and list with all comments for that object ?

like image 902
CappY Avatar asked Jan 20 '14 19:01

CappY


2 Answers

Create a service:

// 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...
    }
}

Declare a service:

# 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

Use a service in controller:

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
        );
    }
}

or in twig, if you pass your service in template like above in render() function:

#AcmeHelloBundle:Blog:index.html.twig

{{ widget.getComments()|raw }}

And usefull to read the docs about How to work with Scopes

like image 124
Victor Bocharsky Avatar answered Nov 09 '22 16:11

Victor Bocharsky


I have done it another way. I registered Twig Extension with function {{ comments(object) }}

The function is registered that way

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

That way I don't need to specify |raw filter.

like image 27
CappY Avatar answered Nov 09 '22 16:11

CappY