Laravel Blade @foreach不起作用 [英] Laravel Blade @foreach not working
问题描述
到目前为止,我正在学习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.
推荐答案
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屋!