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?
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.
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).
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.
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' }} .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With