Introduction to Laravel's method of configuring dual templates (code example)

01-28-2024

What this article brings to you is an introduction to Laravel's method of configuring dual templates (code example), which has certain reference value. Friends who need it can refer to it and hope to help you. In the process of development, from time to time, some projects need to use two sets of templates.

For example, PC and Mobile use different template files to achieve the best user experience.

In this case, how should we configure Laravel's template file?

1. install whichbrowser/parser portal: WhichBrowser/Parser-PHP is used to judge PC or Mobile devices and load different templates as needed.

composer require whichbrowser/parser

2. Use artisan command to create a new Middleware.

After execution, middleware files will be generated in the app/Http/Middleware directory.

php artisan make:middleware Template

3. Edit the Template.php document.

class Template { protected $except = []; public function handle($request, Closure $next) { $result = new WhichBrowser\Parser(getallheaders()); //Returns true if it is a desktop type. $isDesktop = $result->isType('desktop'); if ($isDesktop) { //Load the template file on pc side. $path = resource_path('views/pc/'); } else { //Load the template file on the mobile side. $path = resource_path('views/mobile/'); } //Get the View Finder instance $view = app('view')->getFinder(); //Redefine the view directory $view->prependLocation($path); //Return the request return $next($request); } }

4. Finally, register the middleware. Register the middleware as needed in the app/Http/Kernel.php class.

Such as registering global middleware:

protected $middleware = [ \App\Http\Middleware\Template::class, ];

Done, you can load different template files according to different devices.

Only in this way can different templates be loaded according to different devices in control.

return view('registration.index', $data);

For example, to open a webpage from a PC device, load the template/resources/views/PC/registration/index.blade.php.

For example, to open a webpage from a mobile device, load the template/resources/views/mobile/registration/index.blade.php.

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us