Layouts and Blocks
Alloy has view layouts that wrap around content and templates returned from Controller methods. These layouts are a single file that includes both the header and footer, and a placeholder for where the content goes. The resulting content from the main Alloy module dispatch is inserted in the designated content area - effectively having the layout wrapped around it.
Layouts
In an Alloy project, layouts are located in the app/layouts/ folder and are structured and formatted just like regular views, and are instances of the same Alloy\View\Template object that regular views are that are typically returned by a Controller response. The only difference is conceptual - layouts have response content pushed to them through a $content variable, and regular views don't have to do anything special.
Here is an example of a typical layout with blocks:
<?php $asset = $view->helper('Asset'); // If page title has been set by sub-template if($title = $view->head()->title()) { $title .= " - My App"; } else { $title = "My App Default"; } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title><?php echo $title; ?></title> <?php echo $asset->stylesheet('app.css'); ?> </head> <body> <div id="container"> <div id="menu"> <?php echo $view->block('context_menu'); ?> </div> <div id="content"> <?php echo $content; ?> </div> <div id="sidebar"> <?php echo $view->block('sidebar', function() { echo "Default Sidebar Content"; }); ?> </div> </div> </body> </html>
Blocks
Blocks are named chunks of content that can be generated from within any view template anywhere in your application, and displayed in any other template that is included in the current request, like a layout. Block content is persistent for the current request and static to the view template objects, so views don't even have to be related to each other for one view to set content to be displayed in another view's named block. The typical use case is a Controller response template setting custom content in an area of a layout, like a context-sensitive navigation menu or custom header, footer, or sidebar content.
<?php // Sidebar content $view->block('sidebar')->content(function() use($view) { ?> <p>As with most native Australian animals, the koala cannot legally be kept as a pet in Australia or anywhere else. The only people who are permitted to keep koalas are wildlife carers and, occasionally, research scientists. These individuals are issued with special permits to care for koalas, but have to return them to the wild when they are either well enough or, in the case of joeys, old enough</p> <p><?php echo $view->link('Koala Bears', 'http://en.wikipedia.org/wiki/Koala_bear'); ?></p> <?php }); ?>
