【问题标题】:Laravel Blade @foreach not workingLaravel Blade @foreach 不工作
【发布时间】:2014-06-14 23:52:09
【问题描述】:

我正在学习 Laravel 4,到目前为止一切顺利。但是由于某些奇怪的原因,刀片的 @foreach 似乎不适用于简单的查询。我的代码是:

路线:

Route::get('/users', function(){

    $users = User::all();

    return View::make('users/index')->with('users',$users);

});

现在在 index.blade.php 我的代码是:

  @foreach ($users as $user)

        <p>User: {{ $user->username }}</p>

  @endforeach

奇怪的是,当我将对象转储到视图中时,它确实起作用了:

{{ dd($users->toArray())}}

数据库数据以数组形式显示。

我不确定我在这里做错了什么,这几乎是初学者教程中的代码。

【问题讨论】:

  • 使用 foreach 循环时遇到的错误/问题是什么?
  • 什么都没有显示,也没有错误日志。
  • 确保你已经使用index.blade.php作为view文件的名称,我怀疑你错过了blade它。
  • 如果将View::make('users/index') 替换为View::make('users.index') 会怎样
  • username 字段在$user/User 模型中可能为空,请检查其他字段/属性。

标签: php laravel laravel-4


【解决方案1】:

你应该使用template/layout(但你没有根据你的view on Github使用)并且子视图应该扩展它,例如,你的index.blade.php视图应该看起来像这样:

// index.blade.php
@extends('layouts.master')
@section('content')
    @foreach ($users as $user)
        <p>User: {{ $user->username }}</p>
    @endforeach
@stop

现在确保,在您的 app/views/layouts 文件夹中,您有一个 master.blade.php 布局,并且它包含如下内容:

// master.blade.php
<!doctype html>
<html class="no-js" lang="">
    <head>
        <style></style>
    </head>
    <body>
        <div class='content'>
            @yield('content') {{-- This will show the rendered view data --}}
        </div>
    </body>
</html>

dd($users-&gt;toArray()) 也有效,因为它使用var_dump 转储$user-&gt;toArray() 并使用die 函数退出脚本,dd 表示dump and die

【讨论】:

  • 是的,教程没有提到主视图有点令人困惑,框架看起来很棒。
  • 是的,很好,我喜欢。您也可以like these articles 并查看view composer 和其他文章,可能对您有所帮助(Laravel 相关)。
猜你喜欢
  • 2023-01-10
  • 2015-07-10
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2016-04-14
  • 2018-03-07
相关资源
最近更新 更多