Home > Article > PHP Framework > Detailed explanation of laravel's view function
The traditional MVC model is divided into models, controllers and views. Views are used to store HTML files. Laravel's view files are stored in the resources/views directory. Let's create a video
Create a view
Route::get('/v1', function () { return view('v1'); });
Create the resources/views/v1.blade.php file with the following content:
<html> <body> <h1> hello world </h1> </body> </html>
Subdirectory view
For the view of a subdirectory, use the . operator to specify it. For example, resources/views/home/index.blade.php, then you need to
return view(home.index);
to determine whether the view exists
Sometimes it is necessary to determine To check whether a view exists, you need to use the exists method. As follows:
if (view()->exists('v1')) { // }
Pass data to the view
Generally, there are very few cases where pure HTML is used in the view, and it is often necessary to pass parameters to the view. . In laravel, there are several ways to pass parameters to views. You can pass an associative array in the second parameter in the view function, so that the view can get the data, as follows:
return view('v1', ['name' => 'laravel', 'act' => 'study']);
To use parameters in the view, you need to use {{$key}}
<p>{{$act}} {{$name}}</p>
You can also use the with method to pass parameters, which supports coherent operations
return view('v1') ->with(['name' => 'laravel', 'act' => 'study']) ->with('title', 'php.cn');
All views share data
In multiple Sharing data within a view is a common requirement and can be set in app/Providers/appServiceProvider;
public function boot() { // view()->share('key', 'val'); }
View synthesizer and constructor
The view synthesizer and constructor are similar to the constructor and destructor in the PHP class. The synthesizer is a piece of business logic executed before the view is displayed, while the constructor is a piece of business logic executed after the view is rendered.
Because they are not used much, I will not demonstrate how to operate the view's synthesizer and constructor here. Interested children can check the documentation themselves.
Compiled files of views
View files need to be compiled, and the files generated by compilation are saved under the storage/framework/views file. By default, view files are compiled on demand, but when the compiled file does not exist or the view file is modified, the view file will be recompiled. However, there is a performance impact to compiling the view files on a fetch request. Therefore, laravel provides a tool to compile all view files at once.
php artisan view:cache
Corresponding to this direction is the compiled file command to delete all views
php artisan view:clear
Recommended tutorial: "laravel framework"
The above is the detailed content of Detailed explanation of laravel's view function. For more information, please follow other related articles on the PHP Chinese website!