shAkur
shAkur

Reputation: 1002

Laravel blade concatenate string if variable is not empty

I'm trying to add an id attribute to a link if a given variable is not empty. To do so I'm using the inline-if sentence.

<li><a {{ $link['element_id'] }}  != "" ? {{"id=" . $link['element_id'] }} : '' href="{{ url($link['url']) }}">{{$link['name']}}</a></li>

Output: enter image description here

Upvotes: 1

Views: 5127

Answers (4)

Dimitar Stefanov
Dimitar Stefanov

Reputation: 131

I believe you issue is that it is out of the php itself. Did you try using

<li><a {{ $link['element_id'] != "" ? 'id=' . $link['element_id'] : ''}} href="{{ url($link['url']) }}">{{$link['name']}}</a></li>

And also a good practice is to use one type of quotes in the php code preferably single ones.

Upvotes: 3

Benjamin Brasseur
Benjamin Brasseur

Reputation: 558

Try something like this :

<li>
    <a @if($link['element_id']!="") {{"id=" . $link['element_id'] }} @endif href="{{ url($link['url']) }}" >
        {{$link['name']}}
    </a>
</li>

But if you really want to do it via "inline-if" (this should work):

Your issue is that your are not putting the php between the brackets.

<li>
    <a {{ $link['element_id']!= "" ? "id=" . $link['element_id'] : ''}} href="{{url($link['url'])}}">
        {{$link['name']}}
    </a>
</li>

Upvotes: 1

flipbox
flipbox

Reputation: 83

This one should works:

<li>
    <a id="{{ $link['element_id'] !== '' ? $link['element_id'] : null }}" href="{{ url($link['url']) }}">
        {{ $link['name'] }}
    </a>
</li>

Upvotes: 1

Lloople
Lloople

Reputation: 1844

You can use conditional inside the blade mustache syntax:

<li><a id="{{ $link['element_id'] != '' ? $link['element_id'] : '' }} href="{{ url($link['url']) }}">{{$link['name']}}</a></li>

Upvotes: 1

Related Questions