phpsymfonyreplaceannotationsrender

Symfony 3 - replace string after render view (annotation)


I need replace string in view after rendered. My all controllere use annotaion @Template("path").

My controller:

...
class AboutController extends Controller
{
    /**
     * @Route("/about-us", name="about")
     * @Method("GET")
     * @Template("@AppBundle/Resources/views/About/index.html.twig")
     */
    public function indexAction()
    {
    }
}
...

I know to do it without annotaion:

...
class AboutController extends Controller
{
    /**
     * @Route("/about-us", name="about")
     * @Method("GET")
     */
    public function indexAction()
    {
        $content = $this->renderView('AppBundle/Resources/views/About/index.html.twig', []);
        $content = str_replace('my text', 'my new text', $content);

        return new Response($content);
    }
}
...

How I can do it with annotaion (@template)?


Solution

  • I think you should use Symfony's Event system onKernelResponse

    This will allow you to grab the response after controller action return it and modify the response before sending it.

    To subscribe an event follow Syfmony's doc example. You did not tell us which version of Symfony you are using, those links are 3.4.

    Hope this helps.