kalites kalites - 6 months ago 59
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()

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


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

        posts_service: '@app_posts_service'

Then define the service

        class: AppBundle\Service\PostsService
        arguments: ["@doctrine"]

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

    - { 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

Then use it in any twig file like:

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