How would one go about setting a header (Content Type) and rendering a twig template without renderView() method in symfony2.X controller?
raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter. This only works if the raw filter is the last filter that is applied to the filter.
Macros are comparable with functions in regular programming languages. They are useful to reuse template fragments to not repeat yourself. Macros are defined in regular templates. Imagine having a generic helper template that define how to render HTML forms via macros (called forms.html ):
I'm not sure if the accepted answer is valid anymore, or if ever was. Anyhow, here's a couple ways of doing it. I've got an XML, and JSON sample for you here.
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
class DefaultController extends Controller{
public function indexAction($x = 0)
{
$response = new Response(
$this->renderView('AcmeMyBundle:Default:index.html.twig', array('x'=>$x)),
200
);
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
//...
or for JSON response
//...
public function indexAction( $x = 0 )
{
$response = new JsonResponse(
array('x'=>$x)
);
return $response;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With