假设我在网站上不止一处有评论。我怎样才能创建类似的东西
{{ render_widget('comments', {"object": object} ) }} ?这将呈现带有该对象的所有注释的表单和列表?
最佳答案
创建服务:
// 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
在 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
);
}
}
或者在 Twig 中,如果您在
render()
中像上面那样在模板中传递您的服务功能:#AcmeHelloBundle:Blog:index.html.twig
{{ widget.getComments()|raw }}
阅读有关 How to work with Scopes 的文档很有用
关于Symfony 如何使用 PHP 和 twig 创建可重用的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21242450/