Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a laravel blade variable without displaying it

In my blade code, I need a counter, to give divs that are rendered by a foreach loop unique id's. For that purpose I created a variable in my blade template like this:

{{ $counter = 0 }}

I use it in the html by just outputting it with {{ $counter = 0 }}

and the later on, I increment it like this: {{ $counter++ }}

It all works like a charm, except that at {{ $counter++ }} it's not only incrementing the variable, it's also outputting it to the view.

is there any way to prevent this?

like image 262
ErikL Avatar asked Jul 18 '16 17:07

ErikL


People also ask

What is __ In Laravel blade?

The __ helper function can be used to retrieve lines of text from language files. You can retrieve lines of text from either key-based translation files (represented as PHP arrays) or from literal, string-based translation files (represented as a JSON object). Replacements are passed as a key/value pair.

Can I use blade without Laravel?

You could download the class and start using it, or you could install via composer. It's 100% compatible without the Laravel's own features (extensions).

What is @yield in Laravel?

In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page.

How do you check if a variable is set or not in Laravel blade?

You can use the @isset blade directive to check whether the variable is set or not. Alternatively, if you have the default value for that variable you can directly use it as {{ $vatiable ?? 'default_value' }} .


1 Answers

At first adding logic on blade templating is a bad practice, but sometimes we are forced to do, in that case you can just use PHP tags for it like this:

<?php $counter++; ?>

Another way to do it on Laravel 5.4 as docs indicate:

In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template:

@php
   $counter++;
@endphp

If you have your positions on the array keys you can use it on the @foreach like this:

@foreach ($variable as $key => $value) 
    //current position = $key
    # code...
@endforeach
like image 151
Troyer Avatar answered Sep 28 '22 01:09

Troyer