【问题标题】:Why can't I have two separate functions returning two different views simultaneously?为什么我不能有两个单独的函数同时返回两个不同的视图?
【发布时间】:2019-05-19 11:17:11
【问题描述】:

我正在使用 Laravel,但我遇到了控制器返回视图的问题。 $aboutUs 有效,但对于 $footerText,我收到一条错误消息:

Undefined variable: footerText (View: 
/Users/user/sublime/blog/resources/views/about- 
us.blade.php)

我做错了什么,我该如何解决?

这里是AboutUsController.php

<?php

namespace App\Http\Controllers;

class AboutUsController extends Controller
{

    public function index()
    {
        $aboutUs = "About Us";

        return view('about-us', compact("aboutUs"));
    }

    public function indexTwo()
    {
        $footerText = "Some more text here";

        return view('footer-content', compact("footerText"));
    }

}

这里是views/about-us.bladephp

@extends('layouts.about-us')

@section('title', $aboutUs)

@section('about-content')
    <div class="container">
        <h1>{{ $aboutUs }}</h1> {{-- This works --}}
        <h1>{{ $footerText  }}</h1> {{-- This doesn't work --}}
    </div>
@endsection

【问题讨论】:

  • 为什么不尝试使用一个函数呢?
  • @MONSTER 你不能在一个函数中返回两个东西
  • 您是否要返回页面特定的页脚数据?为什么不创建一个布局模板来保存您的页眉和页脚数据并将您的页面特定内容包装在其中?

标签: php laravel debugging view laravel-blade


【解决方案1】:

在单个函数中返回 2 个内容时,请尝试使用 with

public function index()
{
    $aboutUs = "About Us";
    $footerText = "Some more text here";


    return view('about-us', compact("aboutUs"))
              ->with('footer-content', compact("footerText"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多