Laravel Blade 中的三元

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25284344/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:41:46  来源:igfitidea点击:

Ternary in Laravel Blade

laravelternary-operatorblade

提问by LeBlaireau

Looking for a ternary operator for blade templates

寻找刀片模板的三元运算符

@if(Auth::check()) ? yes : no @endif

Can't seem to get it to work this works

似乎无法让它正常工作

@if(Auth::check()) yes @else no @endif

suppose there is not much in it for this example, just curious.

假设这个例子中没有太多内容,只是好奇。

回答by Marwelln

You are free to use it with {{ }}.

您可以随意使用它{{ }}

{{ Auth::check() ? 'yes' : 'no' }}

回答by Laurence

This works:

这有效:

{{ Auth::check() ? 'yes' : 'no' }}

回答by Bryce

I know this question was asked a while ago, but this may help somebody.

我知道这个问题是不久前被问到的,但这可能对某人有所帮助。

You can now do this in Laravel 5.

你现在可以在 Laravel 5 中做到这一点。

{{ $variable or "default" }}

Laravel 5 Blade Templates

Laravel 5 Blade 模板

Laravel 5.2 Blade Template

Laravel 5.2 刀片模板

回答by vitr

in addition, here is a nice shortcut ?:, if you you need to print some variable's value or if it's empty some default text

此外,这是一个很好的快捷方式?:,如果您需要打印一些变量的值或者如果它是空的一些默认文本

{{ $value ?: 'Default Value' }}

回答by Chad

For Laravel 5 + php7, you should be using the null coalesce operator as explained in this Laravel News article, like so:

对于 Laravel 5 + php7,您应该使用 null 合并运算符,如这篇 Laravel 新闻文章中所述,如下所示:

{{ $value ?? "Fallback" }}

Before the null coalescing operator, Blade handled the same problem with the “or” operator, which allows a default value when the first value isn't set, separated by an “or”.

在空合并运算符之前,Blade 处理了与“or”运算符相同的问题,它允许在第一个值未设置时使用默认值,用“or”分隔。