Famaxis
Famaxis

Reputation: 73

Extra whitespaces in blade statements. Laravel 8

The problem is, it's not just one variable, but statements with @if, @isset and @foreach directives. I can't remove whitespaces without syntax error. And all these whitespaces are displaying in input fields.

In description field I did this:

  1. Check, if old('description') exists.

  2. If yes, display it.

  3. If not, then check, if variable $post exists (I use this form for store and update methods both).

  4. If yes, display it.

  5. If not, the field remains empty.

     <div class="form-group">
     <label for="description">Description</label>
     <textarea id="description" name="description" rows="3">@if(old('description')){{ old('description') }}@else @isset ($post){{$post->description}}@endisset @endif</textarea>
    
     <div class="form-group">
     <label for="tags">Tags</label>
     <input type="text" name="tags" id="tags"
            value="@isset ($post, $tags)@foreach($post->tagged as $tagged){{$tagged->tag_name}},@endforeach @endisset">
    

I tried package hedronium/spaceless-blade, but it doesn't work with input values.

Upvotes: 0

Views: 1893

Answers (2)

Famaxis
Famaxis

Reputation: 73

I solved my problem, using directive @php.

<textarea id="description" name="description" rows="3">@php
        if(old('description')) {
            echo old('description');
        } elseif (isset($post)){
            echo $post->description;
        } 
    @endphp</textarea>

No more extra whitespaces.

Upvotes: 0

Muhammad Dyas Yaskur
Muhammad Dyas Yaskur

Reputation: 8098

>@if and "@isset will be parsed as string because @ will be parsed as syntax only if not join together with other character except space, new line or tab. You can do if condition without @ inside {{}}.

I have a better solution using ternary operator and null coalescing operator.

change your long code

@if(old('description')){{ old('description') }}@else @isset ($post){{$post->description}}@endisset @endif

to

{{old('description') ?? isset($post)?$post->description:''}}

and change

@isset ($post, $tags)@foreach($post->tagged as $tagged){{$tagged->tag_name}},@endforeach @endisset

to

{{isset($post) ? implode(', ', $post->tagged->pluck('tag_name')->toArray() )):''}}

so the full code:

  <div class="form-group">
  <label for="description">Description</label>
  <textarea id="description" name="description" rows="3">{{old('description') ?? isset($post)?$post->description:''}}</textarea>
</div>


 <div class="form-group">
 <label for="tags">Tags</label>
 <input type="text" name="tags" id="tags"
           value="{{isset($post) ? implode(', ', $post->tagged->pluck('tag_name')->toArray() )):''}}">
</div>

Upvotes: 1

Related Questions