【问题标题】:Pass json data to blade view from controller将 json 数据从控制器传递到刀片视图
【发布时间】:2021-07-09 14:19:16
【问题描述】:

我正在从我的资源文件夹 resources/data/example.json 加载一个 json 文件

public function __construct()
{
    // Load json file 
    $path = base_path('resources/data/rooms.json');
    $content = file_get_contents($path);
    $data = json_decode($content);
}

我的 json 文件是这样的,这是一个简单的例子:[ { "id":"bicycle", "category":"vehicle", "name":"Bicycle One", "images":[ "/img/bike_slider_1.jpg", "/img/bike_slider_2.jpg" ], },

所以现在我想知道如何将其中一些数据传递给视图,例如 bikes.blade.php 看起来像这样: @extends('layouts.default') @section('content') <main>{{ content[1] }}</main>

任何帮助将不胜感激:)

【问题讨论】:

    标签: php json laravel


    【解决方案1】:
        public function index()
        {
            // Load json file 
            $path = base_path('resources/data/rooms.json');
            $content = file_get_contents($path);
            $data = json_decode($content);
        
            return view('bikes', [
                    'items' => $data,
                ]);
        }
    

    内刃

    @foreach ($items as $item) 
        {{ $item->name }}
    @endforeach
    

    【讨论】:

      【解决方案2】:

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

      您可以点击此链接。您已经将 JSON 数据转换为对象。现在只需从控制器传递它。

      return view('yourBladeFile')->with('data ', $data );
      

      现在在刀片文件中,您可以像这样读取它:

      @foreach($data as $item)
        <p> {{$item->name}} </p>
      @endforeach
      

      或其他适合您的方式。

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 2017-09-03
        • 2019-04-13
        • 2019-12-19
        • 1970-01-01
        • 2016-06-25
        • 1970-01-01
        • 2014-08-23
        • 1970-01-01
        相关资源
        最近更新 更多