kalites kalites - 1 year ago 140
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?

Answer Source

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 %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download