How to render a view from a service class in symfony?
I am trying to make a function in my service class that displays a branch page. I tried to do like this: service.yml:
********
parameters:
error.class: AppBundle\Utils\Error
services:
app.error:
class: '%error.class%'
arguments: [@templating]
Error.php (service class):
****
class Error
{
public function __construct($templating)
{
$this->templating = $templating;
}
public function redirectToError($condition,$message)
{
if($condition){
return $this->templating->render('default/error.html.twig',array(
'error_message' => $message,
));
}
}
}
and error.html.twig , which have some random text to see if it gets there.
After that, I get this response from the browser:
Can someone tell me what is the problem?
source to share
YAML can be a little bit when it comes to syntax, make sure you use all spaces (no tabs). And it ensures that each indent is the same number of space characters. Like 2/4/6/8 for each level, or 4/8/12, etc. if you prefer a width of 4.
The code you posted should be fine, but probably something silly as described above. If there is actually a wrong section / parameter in the file symfony should tell you which is unexpected as it actually validates the YAML files on its content.
Allright so ['@templating']
will take care of the YAML parsing error, the next part is how to use the service. This is done using a service container .
The controller has an alias for it and you can do something like:
// required at the top to use the response class we use to return
use Symfony\Component\HttpFoundation\Response;
// in the action we use the service container alias
// short for $this->container->get('app.error');
$content = $this->get('app.error')->redirectToError(true, 'Hello world');
// as your redirectToError function returns a templating->render, which only returns a
// string containing the the rendered template, however symfony
// requires a Response class as its return argument.
// so we create a response object and add the content to it using its constructor
return new Response($content);
A few little things:
$condition
will probably change if it doesn't seem like it shouldn't be in a function, but around a function call, as it seems strange to call redirectToError but there is no error, instead we just call it when we do an error.
And its recommended if you set a class variable to define it ( visibility details ):
class Error {
// visibility public, private, protected
protected $templating;
source to share