You get a bonus - 1 coin for daily activity. Now you have 1 coin

How can you render templates from an action in Symfony? How to render several templates?

Practice




How can templates be rendered from an action in symfony? how to render several templates?

it's very simple
if you just need to output text in Symfony - then

/**
* @Route("/nameact")
* @Template()
*/
public function nameactAction()
{

// ****
return new Response('текст');

}




if you need to output a template in Symfony with variable substitution and with HTTP headers - then

/**
* @Route("/nameact")
* @Template()
*/
public function nameactAction()
{

// ****
return $this->render('FOSUserBundle:Default:nameTPL.html.twig', $resultarray);

}




if you need to output a template in Symfony with variable substitution without HTTP headers - then

/**
* @Route("/nameact")
* @Template()
*/
public function nameactAction()
{

// ****
return $this->renderView('FOSUserBundle:Default:nameTPL.html.twig', $resultarray);

}




if you need to output data in JSON format in Symfony - then

/**
* @Route("/nameact")
* @Template()
*/
public function nameactAction()
{

// ****
return new Response(json_encode(array());

}




if you need to output a "page not found" message in Symfony - then

/**
* @Route("/nameact")
* @Template()
*/
public function nameactAction()
{

// ****
throw $this->createNotFoundException($message);

//****
}



If you need to redirect instead of outputting something, the action should return the following

return $this->redirect($this->generateUrl('fos_user_registration_register'),302);




don't forget to include

use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpFoundationResponse;


if you're returning only an array, then the template name must match the action's name


/**
* @Route("/nameact")
* @Template()
*/
public function nameactAction()
{

// ****
return $resultarray;

}



the template nameact.html.twig must exist

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)