我的 laravel 应用程序有一个布局。我有四个扩展此布局的 View 。但是,我希望每个 View 都有不同的背景图像。
我的 Layout.blade.php 文件如下所示:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TITLE</title>
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" />
<link rel="stylesheet" href="{{ asset('css/style.css') }}" />
</head>
<nav>
<!-- NAV STUFF HERE -->
</nav>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
我在 style.css 文件中设置了我的 body 样式:
body{
background-image: url('/images/image.png');
background-size: cover;
}
这种样式化技术不言而喻地为每个 View 提供了相同的背景图像,这是我不想要的。我希望能够为每个 View 设置不同的背景图像。
那么我如何设置每个页面具有不同的背景图像,但仍保持它们扩展通用布局的功能?谢谢。
最佳答案
而不是像这样设置 body
的样式:
body{
background-image: url('/images/image.png');
background-size: cover;
}
将样式应用于您的 View
的父元素,如下所示:
.view_parent_image1{
background-image: url('/images/image1.png');
background-size: cover;
}
.view_parent_image2{
background-image: url('/images/image2.png');
background-size: cover;
}
然后像这样使用它:
// View 1
@extends('layouts.master')
@section('content')
<div class='view_parent_image1'>
</div>
@stop
在另一个 View 中使用类 view_parent_image2
代替等等:
// View 2
@extends('layouts.master')
@section('content')
<div class='view_parent_image2'>
</div>
@stop
更新:另一种方法:
// In your master layout
<body class='{{ $bodyClass or "default" }}'>
加载 View 时:
return View::make('viewname')->with('bodyClass', 'imageOne');
CSS:
.default { ... }
.imageOne { ... }
您还可以从 BaseController
共享一个全局变量:
View::share('bodyClass', 'imageOne');
最后(也许是最好的)您可以创建 View 编辑器来自动设置 View 的类
:
View::composers(array(
'ViewComposers@homeViewComposer' => 'home.index',
'ViewComposers@aboutViewComposer' => 'about.index',
));
class ViewComposers {
public function homeViewComposer($view)
{
return $view->with('bodyClass', 'homeViewClass');
}
public function aboutViewComposer($view)
{
return $view->with('bodyClass', 'aboutViewClass');
}
}
CSS
.homeViewClass { ... }
.aboutViewClass{ ... }
如果您需要有关如何创建和放置 view composers
的详细信息,那么您可以 follow this answer .
关于html - 使用相同的 Laravel 布局时的不同背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23984588/