2016-10-19 59 views
0

我正在使用Symfony 3和Twig。Symfony Twig Call Continer

在每一個我需要對實體的呼叫路由:

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

有一種方法,我可以在全球做到這一點? 並從樹枝而不是在路線中調用它?

回答

1

你可以寫一個服務,將做到這一點,並注入其作爲全球

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

然後定義服務

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

確保你的服務文件得到導入到你的配置樹枝:

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

然後定義服務:

// 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(); 
    } 
} 

然後用它在任何樹枝文件,如:

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

的感謝!當我添加行到config.yml我得到:服務「twig」具有對不存在的服務「app_posts_service」的依賴。 – kalites

+0

wroks!你可以發送給我下午的電話號碼 – kalites

+0

嗎? – kalites