1
votes

I'm learning Zend Framework 2 and walked already through the famous Album tutorial. So I've a basic understanding what’s going on but unfortunately I miss a fundamental part about layouts.

I want to build a basic Web application that supposed to have:

  1. A homepage for guests
  2. A complete different hompage for logged in user
  3. Divide the layout in header, content, footer

I've installed the ZF2 Skeleton Application and the Zfcuser module. The site and registration pages show up like they supposed to.

I'll find all layout files in Application/view and the configured path in Application/config/module.config.php

But I have still a couple of questions:

  1. How can I divide the layout into header, content, footer? (Different templates)
  2. How can I create my own layout.phtml? Is it best practice to overwrite the one in Application/view or should I create my own module that overwrites the complete view_manager array?
  3. How can I load a different layout according a user is logged in or not? The zfcUser module provides an helper for that:

    if(!$this->zfcUserIdentity()):

But I don't know where to add it.

Thank you so much in advance. And if anyone has a good link to a tutorial - please post it. I really appreciate it.

1

1 Answers

4
votes
  1. For dividing layout template into blocks, you can use Partial view helper (zf2 docs), simple example of layout template:
<html>
    <body>
        <?php
            // render template from view/partials/header.phtml
            echo $this->partial('partials/header');
        ?>

        <?php echo $this->content; ?>

        <?php
            // render template from view/partials/footer.phtml with some additional variables from layout scope
            echo $this->partial('partials/footer', [
                    'variable' => 'value',
            ]);
        ?>
    </body>
</html>
  1. If it should be new different layout template, just create new one in view/layout path of your module and use it like I showed you above (layout controller plugin). If you want overwrite layout template (or any other template) from 3rd party module, you can do it in ViewManager config (zf2 docs), example with overwriting login template from ZfcUser module:
// module.config.php
'view_manager' => [
    'template_map' => [
        'zfc-user/user/login' => '/path/to/custom/login-template',
    ],
],
  1. There is Layout controller plugin (zf2 docs), which allows you changing the layout per controller action. For example, in your home page controller action, you can set different layout for for logged users, like this:
if($this->zfcUserIdentity()) {
    $this->layout('layout/members');
}

Definitely take a look at this (incomplete) ZF2 Quick Start rewrite with some best practices.