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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With