Views are used to render the contents of a page – or, in other words, values from page fields and any markup that is specific to a single template and thus shouldn't be in the layout file or partial files. Views are specific to a single template, and each template may have multiple views (if you want to render its contents in multiple ways).
Views have access to parameters passed from the Controller to the $view API variable in their local scope ($this->parameter_name
), as well as ProcessWire's API. That being said, it is recommended that you avoid any sort of "business logic" in your views, even though the view files are indeed (by default) regular PHP files.
Moving code to Controllers and dedicating views to markup generation only – meaning that they mostly contain markup, echo statements, and simple control structures (if, else, foreach, etc.) – is an easy way to maintain separation of concerns.
Example view file
A simple view file could look like this (/site/templates/views/home/default.php):
<?php namespace ProcessWire; ?>
<?= $page->main ?>
<?php if ($page->aside): ?>
<aside>
<?= $page->aside ?>
</aside>
<?php endif; ?>
Views and layouts keep things DRY
When used in unison, views and layout files are a simple way to keep you from repeating yourself – or, in other words, follow the principle of DRY.
A couple of lines of code – e.g. include "header.php"
and include "footer.php"
– in every view file may sound like a relatively small thing, but what if you later on decide to rename those include files – or better yet, decide that you need more common files for all of your views?
That's a whole lot of updating right there, but had you instead included them in a layout file, you could've just updated that single file and be done with it. For this reason alone it's usually better to have common stuff defined once and then have the case-by-case content injected into this common frame – not the other way around.
As we explain in the layouts section of the docs, this approach can also make it easier to grasp the big picture: when most of your basic layout is in one file, it's pretty easy to see what's going on at that level. Then you can start digging into what each template might be adding to the mix via its unique view files.