2014-01-20 3 views
5

웹 사이트의 여러 지점에 주석이 있다고 가정 해 봅시다. {{render_widget ('comments', { "object": object})}} 같은 것을 어떻게 만들 수 있습니까? 그러면 해당 객체에 대한 모든 주석이있는 양식과 목록이 렌더링됩니까?symfony PHP와 나뭇 가지로 재사용 가능한 위젯을 만드는 법

# src/Acme/HelloBundle/Resources/config/services.yml 
parameters: 
    # ... 
    my_widget.class: Acme\HelloBundle\Service\Widget 

services: 
    my_widget: 
     class:  "%my_widget.class%" 
     arguments: ["@service_container"] 
     # scope: container can be omitted as it is the default 

컨트롤러의 서비스를 사용 :

// src/Acme/HelloBundle/Service/Widget.php 
namespace Acme\HelloBundle\Service; 

use Symfony\Component\DependencyInjection\ContainerInterface; 

class Widget 
{ 
    protected $container; 

    public function __construct(ContainerInterface $container) 
    { 
     $this->container = $container; 
    } 

    public function getComments() 
    { 
     $request = $this->container->get('request'); // use service_container to access request, doctrine, twig, etc... 
    } 
} 

이 서비스를 선언 :

+0

[서비스] (http://symfony.com/doc/current/book/service_container.html)를 사용하려고 시도했을 수 있습니다. –

+0

그리고 나서이 서비스를 가지 템플릿에 전달하십시오. –

+0

@Victor 제발, 예제 코드를주세요. :) – CappY

답변

5

서비스를 만들기

namespace Acme\HelloBundle\Controller; 

class BlogController { 

    public function getPostAction($id) { 
     // get post from db 
     $widget = $this->get('my_widget'); // get your widget in controller 
     $comments = $widget->getComments(); // do something with comments 

     return $this->render('AcmeHelloBundle:Blog:index.html.twig', 
      array('widget' => $widget) // pass widget to twig 
     ); 
    } 
} 

또는 나뭇 가지에

, 당신은 템플릿에 서비스를 전달하는 경우 위의 render() 기능 :

#AcmeHelloBundle:Blog:index.html.twig 

{{ widget.getComments()|raw }} 

그리고 유용한내가 그것을 다른 방법을 수행 한 How to work with Scopes

+0

나는 그것을 시도합니다. :) 정말 원시 필터를 사방에 추가하고 싶지 않습니다 ... – CappY

+0

그리고 어떻게 Twig에서 서비스의 인스턴스를 얻을 수 있습니까? – CappY

+0

제가 할 생각이지만, 아직 원시 필터를 사용하지 말라는 제안을 찾지 못했습니다. 찾은 경우 - 말해봐) –

1

대한 문서를 읽을 수 있습니다. 원시 필터 | I는 함수가 그런 식으로

'comments' => new \Twig_Function_Method($this, 'comments', array(
     'needs_environment' => true, 
     'is_safe' => array('html') 
      )) 

내가 지정할 필요가 없습니다 그 길을 등록 기능 나뭇 가지 확장 {{의견 (객체)}}

등록.

+0

'{{comments (object)}}'에서'object'는 무엇입니까? –

+0

가변? : D 주석 처리 된 객체 – CappY

관련 문제