Ø In a few of the route closures we’ve looked at so
far, we’ve seen something along the lines of return view('account'). What’s
going on here?
Ø If you’re not familiar with the
Model–View–Controller (MVC) pattern, views (or templates) are files that
describe what some particular output should look like.
Ø You might have views for JSON or XML or emails, but
the most common views in a web framework output HTML.
Ø In Laravel, there are two formats of view you can
use out of the box: plain PHP, or Blade templates (see Chapter 4).
Ø The difference is in the filename: about.php will
be rendered with the PHP engine, and about.blade.php will be rendered with the
Blade engine.
Ø Once you’ve loaded a view, you have the option to
simply return it (as in Example 3-17), which will work fine if the view doesn’t rely on
any variables from the controller.
Route::get('/', function ()
{
return view('home');
});
Ø This code looks for a view in
resources/views/home.blade.php or resources/views/home.php, and loads its
contents and parses any inline PHP or control structures until you have just
the view’s output.
Ø Once you
return it, it’s passed on to the rest of the response stack and eventually returned
to the user.
Route::get('tasks', function () {
return view('tasks.index')
->with('tasks', Task::all());
});
Ø This closure loads the resources/views/tasks/index.blade.php
or resources/views/tasks/index.php view and passes it a single variable named tasks,
which contains the result of the Task::all() method.
Using View Composers to Share Variables with Every View
Ø There may be a variable that you want accessible to
every view in the site, or to a certain class of views or a certain included
subview — for example, all views related to tasks, or the header partial.
Ø It’s possible to share certain variables with every
template or just certain templates, like in the following code:
view()->share('variableName',
'variableValue');
To learn more, check
out “View Composers
and Service Injection”
No comments:
Post a Comment