当前位置: 首页 > 后端技术 > PHP

Laravel配置双模板

时间:2023-03-30 04:11:12 PHP

在开发过程中,时不时会有一些项目需要使用两套模板,比如PC端和移动端使用不同的模板文件,以达到最佳的用户体验。那么在这种情况下,我们应该如何配置Laravel的模板文件呢??1。安装whichbrowser/parser传送门:whichBrowser/Parser-PHP用于判断PC或Mobile设备,根据需要加载不同模板/Http/Middleware目录生成中间件文件phpartisanmake:middlewareTemplate3.编辑Template.php文件classTemplate{protected$except=[];publicfunctionhandle($request,Closure$next){$result=newWhichBrowser\Parser(getallheaders());//如果是桌面类型,返回true$isDesktop=$result->isType('desktop');if($isDesktop){//在pc端加载模板文件$path=resource_path('views/pc/');}else{//在移动端加载模板文件$path=resource_path('views/mobile/');}//获取取景器实例$view=app('view')->getFinder();//重新定义视图目录$view->prependLocation($path);//返回请求return$next($request);}}4。最后在app/Http/Kernel中注册中间件在.php类中按需注册中间件,比如注册全局中间件:protected$middleware=[\App\Http\Middleware\Template::class,];完成后,在控件中可以根据不同的设备加载不同的模板文件这样就可以根据不同的设备加载不同的模板returnview('registration.index',$data);例如,从PC设备打开网页:加载/resources/views/pc/registration/index.blade.php模板如果从移动设备打开网页:加载/resources/views/mobile/registration/index.blade.php模板原文:Laravel配置双模板