VIEWS

Ø 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.
THREE WAYS TO LOAD A VIEW()
There are three different ways to return a view. For now, just concern yourself with view(), but if you ever see
View::make(), it’s the same thing, and you could also inject the Illuminate\View\ViewFactory if you prefer.

Ø 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.
Example 3-17. Simple view() usage                                                                                             
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.
Ø But what if you need to pass in variables? Take a look at Example 3-18.
Example 3-18. Passing variables to views                                                                                    
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.
Ø  Task::all() is an Eloquent database query we’ll learn about in Chapter 8.

Using View Composers to Share Variables with Every View

Ø Sometimes it can become a hassle to pass the same variables over and over.
Ø 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

=>SEO

1.  Syllabus 2.  Unit Wise Question/Material 3. Paper 4. Previous Paper