Following my last question I can't manage to call the service from the template. I did exactly like in the answer, but I get 'Variable "newmessages" does not exist' in the template.
I also tried returning the service in the parent template, but the parent is never called since there is no request to it, the requests are done only to child templates.
public function indexAction(){
$locationService = $this->container->get('newmessages');
return $this->render(
'MedAppCrudBundle:UserBackend\Message:index.html.twig',
array('newmessages'=>$locationService->methodToCalculate())
);
}
How to call service from parent template? The answer from last question doesn't work.
You can expose your service as a twig function and use it in the twig statement. See the full doc here. As example, define an extension as:
services.yml
And implement it as follow:
Then you can use it in the twig as:
Hope this help
The answer to your question is quite simple. You expose the service as a twig global variable. Based on your example, you should add something similar to your
config.yml
To use it in your twig, you would just write
{{ newmessages.methodToCalculate() }}
.You can read more about this in the How to Inject Variables into all Templates documentation page.
Here is a more detailed example: