'How to render html from a @foreach loop in a textarea
Using Laravel 8 livewire, I need to render a list of name ($list) on per line in a textarea. I do this
<div class=" border border-red-800 rounded-lg mt-8 p-4 w-full bg-green-300">
<form>
<textarea rows="10" class="w-full bg-yellow-100">
@foreach ($list as $maltproducer)
{{$maltproducer->name}}
@endforeach
</textarea>
<x-input.group label="Producer" for='name' :error="$errors->first('name')"
class="flex flex-col w-full p-2 border border-jbrown-peachpuf bg-jbrown-darker rounded-md ">
<x-input.text wire:model="name" type="text" class="" name="name" id="name" value="" />
</x-input.group>
<button wire:click.prevent="store()" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Add this
producer</button>
</form>
</div>
The name are displayed one per line but they are not at the beginning of the line. To have them at the beginning of the line, I have to move my source code to the beginning of the line as here below.
@foreach ($list as $maltproducer)
{{$maltproducer->name}}
@endforeach
This is not acceptable as the file could be formatted differently by the code editor without me even be aware of it.
I tried various thing such as
@foreach ($list as $maltproducer)
<p>{{$maltproducer->name}}</p>
@endforeach
but in this case the <p>
markup is displayed but not interpreted.
I also tried {!!$maltproducer->name!!}
, {!!<p>$maltproducer->name</p>!!}
etc. but I could never manage to get the good result i.e to have one name per line at the beginning of the line.
What is the solution ?
Solution 1:[1]
A textarea renders everything between its tags as the value - this includes spaces, tabs and newlines. So you want to print each line without any spaces before or after the actual value you want. To best accomplish this, is to print the output without any "pretty" format in your code.
We can achieve that by plucking the field from the collection you want to print, then implode that with a newline as the glue. In PHP, that would look like
implode("\n", $list->pluck('name'))
Then its just a matter of printing that directly between the textarea, without any spacing or newlines.
<textarea rows="10" class="w-full bg-yellow-100">{{ implode("\n", $list->pluck('name')) }}</textarea>
Even more Laravel-ish, using the implode()
method on the collection directly,
<textarea rows="10" class="w-full bg-yellow-100">{{ $list->implode('name', "\n") }}</textarea>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |