title: ZF2: Switching Layouts Based on Idenitity - which event to use
body: <p>To date I have had a single layout in my application, configured in module.config.php as follows:</p>
  
  <pre><code>  'view_manager' =&gt; array(
          'template_map' =&gt; array(
              'layout/layout' =&gt; __DIR__ . '/../view/layout/layout.phtml',
          ),
  </code></pre>
  
  <p>I am now trying to switch the layout based on whether a user is logged in or not.  This information is available in my <code>Core\Auth</code> service, and I am using it in my <code>module.php</code> as follows:</p>
  
  <pre><code>public function onBootstrap(MvcEvent $e)
  {
          ...
  
          $eventManager-&gt;attach('dispatch', function ($e) {
          $application = $e-&gt;getApplication();
          $auth = $application-&gt;getServiceManager()-&gt;get('Core\Auth');
  
          if (!$auth-&gt;isLoggedIn()) {
              $viewModel = $e-&gt;getViewModel();
              $viewModel-&gt;setTemplate('layout/public');
          }
      }, -1000000);
  }
  </code></pre>
  
  <p>The problem is that I don't know which event to attach it to, and which priority to use.  If I attach it to:...</p>
  
  <ul>
  <li>...the bootstrap or route event, it gets overridden</li>
  <li>...the dispatch event with a high priority it gets overridden</li>
  <li>...the dispatch event with a low priority, it overrides any layout changes that controller actions might make, e.g. $view->setTerminal(true)</li>
  <li>...the render event, (again) it overrides changes made by actions</li>
  </ul>
  
  <p>Where should I be attaching it?  And with what priority?</p>