导航栏品牌中的Laravel动态页面标题


Laravel dynamic page title in navbar-brand

我有layouts.app.blade.php,其中有<html><body>标记以及<nav>
<body>中,我为每个页面生成内容,所以他们基本上扩展了这个app.blade.php。
所有基本的Laravel东西,所以现在我有了这个:

 <div class="navbar-header">
    <!-- Collapsed Hamburger -->
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#spark-navbar-collapse">
        <span class="sr-only">Toggle Navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <!-- Branding Image -->
    <a class="navbar-brand" href="/">
        *Dynamic page title*
    </a>
</div>
// ...
@yield('content')

我想用这个<a class="navbar-brand">来显示我的页面标题。因此,这意味着它必须为这个"parent.blade.php".中加载的每个模板(使用@yield('content'))进行更改

使用Laravel 5.2我该如何做到这一点?

非常感谢

如果这是下面的母版页标题

<html>
<head>
    <title>App Name - @yield('title')</title>
</head>
<body>
    @section('sidebar')
        This is the master sidebar.
    @show
    <div class="container">
        @yield('content')
    </div>
</body>

然后你的页面标题可以在你的刀片页面中更改,就像下面的一样

@extends('layouts.master')
@section('title', 'Page Title')
@section('sidebar')
@parent
<p>This is appended to the master sidebar.</p>
@endsection
@section('content')
<p>This is my body content.</p>
@endsection

更多信息可以在这里找到Laravel Docs

您可以将其传递给视图,例如

控制器

$title = 'Welcome';
return view('welcome', compact('title'));

查看

isset($title) ? $title : 'title';

或php7

$title ?? 'title';

空合并运算符

在Laravel 9和PHP 8中对我有效的另一种选择是在主布局中使用道具。在我的项目中,我只有一个布局,所以很简单:

<x-layout :title="' - Page Title'">
  <!-- content -->
</x-layout>

然后在layout.blade.php文件中:

@props(['title'])
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Static Title{{$title ?? ""}}</title>
</head>
<body>
  <main>
    {{$slot}}
  </main>
</body>
</html>

在主文件中以如下格式定义此标题,如(masterblade.php)

<title>Vendor | @yield('mytitle') </title>

在第页这里所有公司是我的刀片文件的新标题,你想在这个页面上动态标题

@section('mytitle', 'All Company')

在控制器中声明一个名为title&将其压缩为以下

    public function aboutUs()
    {
        //page title
        $title = 'Project | About Us';
        return view('project.about_us', compact('title'));
    }

在您的视图页面中,调用如下所示的变量

<title>{{ $title }}</title>

您可以尝试放置@stack('title')而不是header.blade.php文件中的title标记然后把它放在你的page.blade.php文件中:

@push('title')
    <title> Home Page</title>
@endpush
@section('main-container')
Your content
@endsection