kalites kalites - 1 month ago 14
Twig Question

Symfony Twig Call Continer

I'm using Symfony 3 with Twig.

In every route I need to make a call to entity:

$posts = $this->getDoctrine()
->getRepository('AppBundle:Posts')
->findAll();


There is a way that I can do this globally?
And call it from the twig instead of in the route?

Answer

You can write a service that will do it and inject it as a twig global

#app/config.yml
twig:
    globals:
        posts_service: '@app_posts_service'

Then define the service

#app/services.yml
services:
    app_posts_service:
        class: AppBundle\Service\PostsService
        arguments: ["@doctrine"]

Make sure your services file is getting imported into your config:

#app/config.yml
imports:
    - { resource: services.yml }

Then define the service:

// src/AppBundle/Service/PostsService.php
namespace AppBundle\Service;

class PostsService
{
    protected $doctrine;
    public function __construct($doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function getAllPosts()
    {
        return $this->doctrine
            ->getManager()
            ->getRepository('AppBundle:Posts')
            ->findAll();
    }
}

Then use it in any twig file like:

{%for post in posts_service.getAllPosts() %}
    {{ post.title }} {# or whatever #}
{% endfor %}