Loop through an array and print out a template for each iteration

时间:2015-11-27 20:39:26

标签: laravel laravel-5

I don't know how to do this and i hope i can get some tips from you.

I get an array with some data from a function. This function is defined in my Controller (HomeController). And the array is built as following:

Array
(
[1] => Array
    (
        [message] => xxx
        [name] => yyy
    )

[2] => Array
    (
        [message] => xxx
        [name] => yyy
    )

[3] => Array
    (
        [message] => xxx
        [name] => yyy
    )

[4] => Array
    (
        [message] => xxx
        [name] => yyy
    )

) 

Now i got this data in my Controller. Next i want to show this data on my view. I want to loop through each data and render it out.

Should i return the array to my view and loop in my view through the array? Or what is the best method for this?

And additionally i got another question. I dont want to just render it out inside the loop. I thought about something like a template. Is it possible to define a template and on every iteration i give the informations from the array to my defined template and then render it out?

The template may look something like this:

<div class="box">
    <h1> $data["name"] </h1>
    <p> $data["message"] </p>
</div>

And then the loop maybe like this:

foreach(...) {
    // the template is rendered here with the array data
    {{ @template($data) }}
}

Thanks for any help!

Solution:

(Thanks to James for his input)

@foreach ($data as $display)
   @include('templatename', $display)
@endforeach

1 个答案:

答案 0 :(得分:1)

你真的很喜欢这个:

foreach(...) {
    // the template is rendered here with the array data
    {{ @template($data) }}
}

现在说我们将数组作为$ data传递给视图,将其更改为正确的blade syntax

@foreach ($data as $display)
<div class="box">
    <h1>{{ $display['name'] }}</h1>
    <p>{{ $display['message'] }}</p>
</div>
@endforeach

如果您引用的数组实际上是从一个雄辩的查询中返回的,那么它将存储在一个对象而不是一个数组中。你只需将其更改为:

@foreach ($data as $display)
<div class="box">
    <h1>{{ $display->name }}</h1>
    <p>{{ $display->message }}</p>
</div>
@endforeach