欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

break, continue, return in blade template LARAVEL BLADE FOREACH CONTINUE AND BREAK 跳过或跳出循环

laravel blade foreach continue and break 跳过或跳出循环

例子:

如果用户id是1就跳过循环,这里我们forelse当没有数据的时候默认输出一些提示信息:
  1. @forelse($data as $item)
  2. @if($item->id == 1)
  3. <?php continue;?>
  4. @endif
  5. <p>{{$item->name}}</p>
  6. @empty
  7. <div>还没有用户请添加</div>
  8. @endforelse

来自 https://www.inbeijing.org/archives/1308

How to use break, continue, return statements is a blade template

malfait.robin

You don't :)

 
bashy
 bashy
2 years ago(1,081,450 XP)

Well, you can do normal PHP inside it but depends on why you'd want to do that... maybe a foreach break?

 
Marwelln

Usually you wouldn't need to, but if you must, use <?php return; ?>

 
lkmadushan

@bashy Yes. Isn't blade support for break statements? Or can we extend blade?

 
bashy
 bashy
2 years ago(1,081,450 XP)

I don't think there's any native support for break, no.

 
intrip

You need to put it inside the php tag: and so on...

 
bashy
 bashy
2 years ago(1,081,450 XP)

@intrip we've said about that already.

 
AlexejKloos

@foreach ($value_array as $value) @if ($value == 'end') @break@endif {{ $value }}
@endforeach

 
eugenevdm

I have the need to break in a foreach after the first loop. I tried:

@if (1==1) @break; @endif

but it didn't work. Instead I just see @break; repeatedly printed on the screen.

 
phildawson
 phildawson
2 years ago(128,000 XP)

That's because break doesnt exist. It's easy to extend.

http://laravel.com/docs/5.1/blade#extending-blade

 
t0ne
 t0ne
1 year ago(9,275 XP)

why do we use blade again?

 
bashy
 bashy
1 year ago(1,081,450 XP)

@t0ne Can use what you want.

 
bartimurugesan

Its simple to Use break inside the blade template. You can just put the php script inside the blade like , It will work and I used this method and got succeed.

 
astierler

Anyone coming in here, you can use @break and @continue inside foreach loops in Blade now. (Not sure if/how long ago this became a change, but it's valid)

 
FoxRocks

@break doesn't seem to work in 5.1, just FYI


普通分类: