gpt4 book ai didi

php - 将数组传递给 Blade 文件并访问其值

转载 作者:行者123 更新时间:2023-12-04 15:50:53 25 4
gpt4 key购买 nike

我刚开始学习 Laravel,我遇到了一个关于跨文件传递值的小问题。

在路由文件中,我有以下函数。

Route::get('/', function()
{
$data = [
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => 'jane@hotmail.com',
'location' => 'London'];

return View::make('hello')->with($data);
});

我将 $data 数组传递给名为 hello.blade.php 的文件。我想打印出这个数组中的所有值。问题是我无法遍历它们并输出其中的值。我收到错误 Undefined variable: data

这是我的 Blade 文件。

@extends('layouts.main')
@section('content')

@foreach ($data as $item)
<li>{{{ $item }}}</li>
@endforeach

@stop

我了解到我可以在 Route 文件中执行类似这样的操作 return View::make('hello')->withData($data); 并让它工作。但我不喜欢像 withData 这样附加变量名的方式。

有没有办法传递数组变量并从 Blade 文件访问它?

谢谢。

最佳答案

你传递了一个关联数组的参数,这告诉 Blade:嘿,把这个数组的键作为变量的名称,并使它们的值对应于数组中键的值。

这意味着,您现在在 View 中有一个值为“Jane”的变量 $first_name,一个值为“Doe”的变量 $last_name 和等等。

这和做的一样

return View::make('hello')
->with('first_name', 'Jane')
->with('last_name', 'Doe');

你明白了。

如果你想传递数组本身,你必须告诉 blade:嘿,获取这个数组并通过给定名称使其在 View 中可用:

return View::make('hello')->with('data', $data);

现在您可以通过变量 $data 在 View 中使用整个数组。

关于php - 将数组传递给 Blade 文件并访问其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26444628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com