laravel 没有 else 的刀片三元运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43418673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Blade ternary operator without else
提问by sarah
I've got a object which has the method hasATest
that returns a boolean and depending on the value I want a button to be enabled or disabled so I thought of doing something like this:
我有一个对象,它具有hasATest
返回布尔值的方法,并根据我想要启用或禁用按钮的值,所以我想做这样的事情:
<button class="btn btn-xs btn-detail btn-activate" name="question_id" value="{{$question->id}}" id="activate{{$question->id}}"
"{{ $question->hasATest() ? disabled : }}"> Activate
</button>
But I don't know what to do about the else. If I remove the :
, an error occurs:
但我不知道该怎么办其他。如果我删除:
,则会发生错误:
"unexpected =" ...
Plus it's not like there's the opposite for disabled.
另外,对于残疾人来说,这并不是相反的情况。
回答by milo526
The ternary operator needs an else
as you already discovered, you could try some statements like null
or in this case ""
to return empty values on the else
.
else
正如您已经发现的那样,三元运算符需要一个,您可以尝试一些语句,例如null
或 在这种情况下""
返回else
.
{{ ($question->hasATest()) ? "disabled" : "" }}
{{ ($question->hasATest()) ? "disabled" : "" }}
回答by Don't Panic
Just use an empty string for the else part.
只需对 else 部分使用空字符串。
<button class="btn btn-xs btn-detail btn-activate" name="question_id" value="{{$question->id}}" id="activate{{$question->id}}"
{{ $question->hasATest() ? 'disabled' : '' }}> Activate
</button>
I think you could also use an @if
for it instead of a ternary.
我认为你也可以使用@if
它代替三元。
<button class="btn btn-xs btn-detail btn-activate" name="question_id" value="{{$question->id}}" id="activate{{$question->id}}"
@if($question->hasATest()) disabled @endif> Activate
</button>
回答by Giulio Bambini
You have problem in this line:
你在这一行有问题:
"{{ $question->hasATest() ? disabled : }}"
Here is the solution:
这是解决方案:
{{ ($question->hasATest()) ? disabled : 'enable' }}
回答by Amit Shah
For those who has to check over the Non-booleanvariable is there or not
对于那些必须检查非布尔变量是否存在的人
e.g. $question->test
returns test name (string) then you can use isset
例如$question->test
返回测试名称(字符串)然后你可以使用isset
<td>
{{ isset($question->test) ? $question->test : __('question.no_test') }}
</td>