Laravel Blade @foreach不起作用 [英] Laravel Blade @foreach not working

查看:394
本文介绍了Laravel Blade @foreach不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我正在学习Laravel 4.但是出于某些奇怪的原因,刀片服务器的@foreach似乎不适用于简单的查询.我的代码是:

I'm learning Laravel 4, so far so good. But for some weird reason blade's @foreach doesn't seem to work for a simple query. My code is:

路线:

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

    $users = User::all();

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

});

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

Now in index.blade.php my code is:

  @foreach ($users as $user)

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

  @endforeach

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

The weird thing is that when I dump the object in the view, it does work:

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

DB数据原始显示为数组.

The DB data is displayed raw as an array.

我不太确定我在做什么错,这是初学者教程中的大部分代码.

I'm not really sure what am I doing wrong here, this is pretty much code from the beginners tutorial.

推荐答案

您应使用template/layout(但您并未根据

You should use a template/layout (but you didn't use according to your view on Github) and child views should extend it, for example, your index.blade.php view should be look something like this:

// 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布局,并且其中包含类似以下内容:

Now make sure that, in your app/views/layouts folder you have a master.blade.php layout and it contains something like this:

// 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->toArray())之所以起作用,是因为它使用var_dump转储$user->toArray()并使用die函数退出脚本,dd表示dump and die.

Also dd($users->toArray()) works because it dumps the $user->toArray() using var_dump and exits the script using die function, the dd means dump and die.

这篇关于Laravel Blade @foreach不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆