Laravel Blade @foreach 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24225344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Blade @foreach not working
提问by Omar Gonzalez
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:
我正在学习 Laravel 4,到目前为止一切顺利。但是由于某些奇怪的原因,blade 的 @foreach 似乎不适用于简单的查询。我的代码是:
Route:
路线:
Route::get('/users', function(){
$users = User::all();
return View::make('users/index')->with('users',$users);
});
Now in index.blade.php my code is:
现在在 index.blade.php 我的代码是:
@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())}}
The DB data is displayed raw as an array.
DB 数据以数组的形式原始显示。
I'm not really sure what am I doing wrong here, this is pretty much code from the beginners tutorial.
我不太确定我在这里做错了什么,这几乎是初学者教程中的代码。
回答by The Alpha
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:
你应该使用一个template/layout
(但你没有根据你在 Github上的观点使用)并且子视图应该扩展它,例如,你的index.blade.php
视图应该是这样的:
// index.blade.php
@extends('layouts.master')
@section('content')
@foreach ($users as $user)
<p>User: {{ $user->username }}</p>
@endforeach
@stop
Now make sure that, in your app/views/layouts
folder you have a master.blade.php
layout and it contains something like this:
现在确保在您的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>
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
.
也dd($users->toArray())
有效,因为它转储$user->toArray()
usingvar_dump
并退出脚本 usingdie
函数,dd
即dump and die
.