Search code examples
phpzend-frameworkmezzio

How to add new layout for admin dashboard


In Zend Expressive, the layout is "default" into "templates" folder.

I would like to add "admin" folder into "templates" folder like that:

  • Templates
    • admin
      • app
        • admin-page.phtml
      • error
        • 404.phtml
        • error.phtml
      • layout
        • default.phtml
    • default
      • app
        • home-page.phtml
      • error
        • 404.phtml
        • error.phtml
      • layout
        • default.phtml

I've tried with the tutorials of Zend expressive to add new layout but no success for me...

class AdminPageHandler implements RequestHandlerInterface
{
    private $template;


    public function __construct(TemplateRendererInterface $template)
    {
        $this->template = $template;
    }

    public function handle(ServerRequestInterface $request) : ResponseInterface
    {

        $data = [
            'admin' => 'layout::admin',
            // or 'layout::admin',
            // or 'layout::alternative',
        ];
        $content = $this->template->render('pages::admin-page', $data);
        return new HtmlResponse($content);
    }
}

How can I add a new layout for my admin dashboard?

I would like to add new layout for my admin dashboard because the HTML script is different of my Home Application.


Solution

  • The template paths can be found in ConfigProvider class => __invoke method, under 'templates' => 'paths' or in getTemplates() method. There you should add a new path:

    /**
         * Returns the templates configuration
         */
        public function getTemplates(): array
        {
            return [
                'paths' => [
                    'app'    => [__DIR__ . '/../templates/app'],
                    'error'  => [__DIR__ . '/../templates/error'],
                    'layout' => [__DIR__ . '/../templates/layout'],
                    'admin'  => [__DIR__ . '/../templates/admin'],
                ],
            ];
        }
    

    then your handler should look something like this

    public function handle(ServerRequestInterface $request) : ResponseInterface
        {
    
            $data = [
                'admin' => 'layout::admin',
                // or 'layout::admin',
                // or 'layout::alternative',
            ];
            $content = $this->template->render('admin::app/admin-page', $data);
            return new HtmlResponse($content);
        }