Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a view from service class in symfony?

I'm trying to make a function in my service class, that render a twig page. I've 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 that have some random text to see if it gets there.

After that I get this answer from browser:

enter image description here

Can somebody to tell me what is the problem?

like image 930
ana.coman93 Avatar asked Jan 31 '26 21:01

ana.coman93


1 Answers

YAML can be a bit iffy when it comes to syntax, make sure your using all spaces (no tab chars). And makes sure every indentation is the same amount of space characters. Like 2/4/6/8 for each level or 4/8/12 etc if you prefer 4 wide.

The code you posted should be fine, but its probably something silly as described above. If it was actually a wrong section/ parameter in the file symfony should tell you what is unexpected as it actually validates YAML files on its content.


Allright so ['@templating'] takes care of the YAML parse error, the next part is how to use a service. Which is done using the service container.

In a controller there is 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 small things:

$condition, is probably likely to change if not it seems it should not be in the function but around the function call, as it seems weird to call an redirectToError but there is no error, instead we just call it when we do have an error.

And its recommended to if you are setting a class variable to define it (details on visibility):

class Error {
    // visibility public, private, protected 
    protected $templating;
like image 60
Jenne Avatar answered Feb 03 '26 23:02

Jenne