Question

I have this piece of code in several Twig templates:

{% if is_granted('IS_AUTHENTICATED_REMEMBERED') == false %}
    {{ render(controller('FOSUserBundle:Security:login')) }}
    {% include 'FOSMapyetBundle:Registration:register.html.twig' with {form:form} %}
{% endif %}

As you may see it receive the parameter form from controllers but here comes the problem in every site I like to use the code lets said in templates I need to pass the parameter form to the view. By now it's only on 15 templates but this make me think, what about if tomorrow should be 20 or 60 or even 100 templates? So what is the best solution to handle this? Twig Extensions? Symfony Services? Any advice or help on this one?

Was it helpful?

Solution

A kernel event listener may work for this. Render your mini template inside the listener and then "inject" it into the final response, similar to how the debug toolbar works:

https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php#L106

Note that this is the approach you may want if you want to modify all pages universally. You can apply checks inside the listener to ignore ajax requests, redirection, and the like. You could also probably implement a simple map that knows which routes should have the response modified.

If you want to explicitly render the template in specific pages, then I agree with Maerlyn.

OTHER TIPS

When you need logic like this, your best option is to render a sub-controller, like you already do with your login form.

Create a RegistrationController in your bundle that creates the form and returns the rendered register.html.twig, then embed it like the line above the include.

You can use Response event, and inject your peace on code at the end of the template.

http://api.symfony.com/2.4/Symfony/Component/HttpKernel/KernelEvents.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top