I want to simplify the laravel blade code, so I think about the way to insert table element with one-liner.
This is what I want to achieve.(These codes don't work the way I expect them to. These two '@include' display same element.)
In the util/insert.blade.php
@section('insert')
<tr>
<th>
{{$th}}
</th>
<td>
<input type="text" name={{$name}} value="{{ $val }}">
</td>
</tr>
@show
In the main.blade.php
<table class="table">
@include('util.insert', ['th' => 'th1', 'name' => 'name1', 'val' => 'val1'])
@include('util.insert', ['th' => 'th2', 'name' => 'name2', 'val' => 'val2'])
</table>
Do you have good suggestion?
CodePudding user response:
You could use blade components to achieve that. Instruction on how to use it can be found in the Laravel documentation: https://laravel.com/docs/8.x/blade#components That way you would be able to create a component for the table header, table row, and so on. However I am not sure that I would agree that it would simplify the blade code, but that is just my opinion.
CodePudding user response:
You can use loop for data
In the main.blade.php
<table class="table">
@include('util.insert', ['data' => [
['th' => 'th1', 'name' => 'name1', 'val' => 'val1'],
['th' => 'th2', 'name' => 'name2', 'val' => 'val2'],
]])
</table>
In the util/insert.blade.php
@section('insert')
@foreach($data as $row)
<tr>
<th>
{{$row['th']}}
</th>
<td>
<input type="text" name="{{$row['name']}}" value="{{ $row['val'] }}">
</td>
</tr>
@endforeach;
@show