Rendering entity automatically ############################## Some entity need to be rendered automatically for a couple of times: a person, a user, ... One can use some twig filter to render those entities: .. code-block:: twig {{ person|chill_entity_render_box }} Define a renderer ================= By default, the object passed through the renderer will be rendered using the :code:`__toString()` method. To customize this behaviour, you have to define a service and tag it using :code:`chill.render_entity`. The rendered is implemented using :class:`Chill\MainBundle\Templating\Entity\ChillEntityRenderInterface`. This interface has 3 methods: * :code:`public function supports($entity, array $options): bool`: return true if the :code:`$entity` given in parameter, with custom options, is supported by this renderer; * :code:`public function renderString($entity, array $options): string`: render the entity as a single string, for instance in a select list; * :code:`public function renderBox($entity, array $options): string`: render the entity in an html box. .. warning:: The HTML returned by :code:`renderBox` **MUST BE SAFE** of any XSS injection. :class:`Chill\MainBundle\Templating\Entity\AbstractChillEntityRender` provides some useful methods to get the opening and closing boxes that should be used. Usage about rendering comment: .. code-block:: php namespace Chill\MainBundle\Templating\Entity; use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable; use Chill\MainBundle\Repository\UserRepository; use Chill\MainBundle\Templating\Entity\AbstractChillEntityRender; use Symfony\Component\Templating\EngineInterface; class CommentRender extends AbstractChillEntityRender { /** * @var \Chill\MainBundle\Repository\UserRepository */ private $userRepository; /** * * @var EngineInterface */ private $engine; public function __construct( UserRepository $userRepository, EngineInterface $engine ) { $this->userRepository = $userRepository; $this->engine = $engine; } /** * @param CommentEmbeddable $entity * @param array $options * * @return string */ public function renderBox($entity, array $options): string { // default options $options = \array_merge([ 'user' => [], 'disable_markdown' => false, 'limit_lines' => null, 'metadata' => true ], $options); if ($entity->getUserId()) { $user = $this->userRepository->find($entity->getUserId()); } return $this->engine ->render( '@ChillMain/Entity/CommentEmbeddable.html.twig', [ 'opening_box' => $this->getDefaultOpeningBox('comment-embeddable'), 'closing_box' => $this->getDefaultClosingBox(), 'user' => $user ?? NULL, 'comment' => $entity, 'options' => $options ] ); } /** * @param CommentEmbeddable $entity * @param array $options * * @return string */ public function renderString($entity, array $options): string { return $entity->getComment(); } public function supports($entity, array $options): bool { return $entity instanceof CommentEmbeddable; } } Logic inside the template: .. code-block:: twig {{ opening_box|raw }}