1

Is it possible to set layout no render in one Action (or set of Actions)?

As I know I can set default layout in config, which will render on every page. I can change it in Action bay passing the 'layout' variable with value, but is it possible to not render layout at all?

class IndexAction
{
    private $template;

    public function __construct(Template $template){ ... }

    public function __invoke($request, $response, $next = null)
    {
        if(!$request->hasHeader('X-Requested-With')){
            $data = ['layout' => 'new\layout']; //change default layout to new one
        }
        else{
            $data = ['layout' => false]; //I need only to return view ?
        }

        return new HtmlResponse($this->template->render(
            'web::index', $data
        ));
    }
}
tasmaniski
  • 4,767
  • 3
  • 33
  • 65
  • If you are trying to return json data there is also the `Zend\Diactoros\Response\JsonResponse`. You use it like this: `return new JsonResponse($dataArray);` – xtreamwayz Oct 01 '16 at 07:37
  • Thanks! But I need to return HTML. In first request (without ajax) need to return Layout + View and if it's ajax request to return only View because I don't want to load layout again. – tasmaniski Oct 01 '16 at 11:30

3 Answers3

1

Now it's available, just set layout = false

    return new HtmlResponse($this->template->render(
        'web::index', 
        ['layout' => false]
    ));
tasmaniski
  • 4,767
  • 3
  • 33
  • 65
0

Actions and templates in Zend Expressive are one-to-one, so I think that the decision whether layout should be rendered or not should be made in the appropriate template itself. Basically, it's a matter of omitting <?php $this->layout('layout::default'); ?> from your action template.

In your particular example, that condition you have should result in choosing different template to be rendered (one that doesn't include layout), instead of a solution with sending a flag to the template. For example:

$templateName = $request->hasHeader('X-Requested-With') 
    ? 'template-without-layout' 
    : 'template-with-layout';

return new HtmlResponse($this->template->render($templateName));
Nikola Poša
  • 153
  • 1
  • 1
  • 13
0

Currently I use plain layout:

<?php

echo $this->content;

There is PR to disable layout rendering.

venca
  • 1,196
  • 5
  • 18