Laravel数据['title']

问题描述 投票:0回答:3

所以我想获得一个标题并在我的控制器上定义它,但是当我请求数据['title']它得到“1”并且我设置“测试”。

我家的控制器

 Route::get('/', 'HomeController@index');

我的行设置$ title

  $data['title']   = "Test";
  return view('home.home', $data);

我的head.blade.php

  <title>{{ $title or Helpers::meta((!isset($exception)) ? Route::current()->uri() : '', 'title') }} {{ $additional_title or '' }}</title>

laravel版本是5.8。我是php world和laravel的新手,谢谢你的帮助!

php laravel
3个回答
1
投票

尝试以更简单的方式将其分解以使视图通过。使用compact并确保在紧凑中使用字符串,而不是变量。像这样:

$title  = "Test";
return view('home.home', compact('title');

尝试一下,应该可以正常工作。


1
投票

将数据传递给视图

您应该使用键/值对传递数组中的数据。在视图中,您可以使用相应的键访问每个值,例如<?php echo $key; ?>。作为将完整数组数组传递给视图助手函数的替代方法,您可以使用with方法将单个数据片段添加到视图中:

 return view('home.home')->with('title', 'Test');

https://laravel.com/docs/5.8/views#passing-data-to-views


-1
投票

抱歉,我迟到了

我已经阅读了每个答案,但每个答案都缺少神奇的类型来传递变量来查看

这个答案似乎是

在声明函数中的大量变量时有点有用

Laravel 5.7。*

例如

public function index()
{
    $activePost = Post::where('status','=','active')->get()->count();

    $inActivePost = Post::where('status','=','inactive')->get()->count();

    $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

    $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

    return view('dashboard.index')->with('activePost',$activePost)->with('inActivePost',$inActivePost )->with('yesterdayPostActive',$yesterdayPostActive )->with('todayPostActive',$todayPostActive );
}

当你看到退货的最后一行时看起来不太好

当你的项目越来越大它不好

所以

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = ['activePost','inActivePost','yesterdayPostActive','todayPostActive'];

        return view('dashboard.index',compact($viewShareVars));
    }

如您所见,所有变量都声明为$viewShareVars数组和View中的Accessed

但是我的功能变得非常大,所以我决定让这条线变得非常简单

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = array_keys(get_defined_vars());

        return view('dashboard.index',compact($viewShareVars));
    }

本机php函数get_defined_vars()从函数中获取所有已定义的变量

array_keys将获取变量名称

所以在你的视图中,你可以访问函数内的所有声明变量

作为{{$todayPostActive}}

所以在你的情况

$data['title']   = "Test";

  return view('home.home', compact(array_keys(get_defined_vars())));

并在你的视图{{$data['title']}}

© www.soinside.com 2019 - 2024. All rights reserved.