Home  >  Article  >  PHP Framework  >  Introduction to how to configure dual templates in Laravel (code example)

Introduction to how to configure dual templates in Laravel (code example)

不言
不言forward
2019-03-02 13:43:173322browse

This article brings you an introduction to the method of configuring dual templates in Laravel (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

During the development process, from time to time we may encounter certain projects that require the use of two sets of templates

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

How should we configure Laravel's template file when encountering this situation?

1. Install whichbrowser/parser Portal: WhichBrowser/Parser-PHP

Used to determine PC or Mobile devices, load different templates on demand

composer require whichbrowser/parser

2. Use the artisan command to create a new Middleware

After execution, the Generate middleware files in the app/Http/Middleware directory

php artisan make:middleware Template

3. Edit the Template.php file

class Template
{
    protected $except = [];

    public function handle($request, Closure $next)
    {
        $result = new WhichBrowser\Parser(getallheaders());
        // 如果是桌面类型, 返回true
        $isDesktop = $result->isType('desktop');
        if ($isDesktop) {
            // 加载pc端的模板文件
            $path = resource_path('views/pc/');
        } else {
            // 加载mobile端的模板文件
            $path = resource_path('views/mobile/');
        }
        // 获取视图查找器实例
        $view = app('view')->getFinder();
        // 重新定义视图目录
        $view->prependLocation($path);
        // 返回请求
        return $next($request);
    }
}

4. Finally register the middleware

in app/Http/Kernel.phpRegister middleware on demand in the class

If you register global middleware:

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

Get it, you can load different middleware according to different devices Template file

Just like this in the control, you can load different templates according to different devices

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

For example, when opening a web page from a PC device: load /resources/views/pc/ registration/index.blade.php template

If you open the webpage from a mobile device: load /resources/views/mobile/registration/index.blade.php template

The above is the detailed content of Introduction to how to configure dual templates in Laravel (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete