The View exists to keep the view script separate from the model & route script. It provides a system of helpers, filters, variables and layout manager.
Commonly, your route script creates an instance of View and assign variables to that instance.
The route script will return output string from view by call render
.
routes/posts.php
views/posts/view.html.php
Usually, you would like to set the directory of view scripts, it make the view script name is shorter when calling the render
,
and make less effort when moving view scripts to another directory. You can change the default directory of all view script by calling setDirectory
method.
By default, the view script directory is your-application-path/views
.
If you call render
with relative script path (render('posts/view')
), the actual script file will be your-application-path/views/posts.view.html.php
.
But if you all render
with absolute script path (start with /
), the view directory is ignore. render('/posts/view')
,
the actual view script path will be /posts/view.html.php
The view script extension is optional when calling render
.
It will assume the extension is .html.php
by default,
but you can changes to whatever you like by calling setExtension
method or just simple calling render
with view script and extension.
Passing variables to view script by calling setVar
, setVars
or addVars
Or simply, just passing the variables to the seconds arguments when calling render
The layout manager is very helpful. For example, when you want all your view scripts wrapped by the header and footer.
You could define the header and footer in separate script called layout
, and the body content is defined in a separate view script file.
views/_layouts/default.html.php
views/posts/view.html.php
routes/posts.php
If you set config the layout and want to disable it in some case, like fetching script content without wrap layout, just call setLayout(false)
You can config the layout in some places:
1. View config file: application/config/view.php
2. Within your route script or route file: routes/posts.php
3. Or inside your view script: views/posts/view.html.php
It is very simple to setting up the nested layouts by calling setLayout()
inside a layout. By this way, you can structure nested layout.
For example, you have the layout (default
) with footer and header like above,
now you want to have a layout (sidebar
) with left sidebar, the sidebar
layout extends default
layout.
views/_layouts/sidebar.html.php
And now you want to render views/posts/view.html.php
with sidebar
layout
routes/posts.php
The output string now is: