在刀片视图中,如果我回显未设置的变量,则会收到错误。所以这个问题通常的答案是:
{{ isset($variable) ? $variable : '' }}
我想知道是否有一种方法可以使其成为刀片模板的默认行为,其中未设置的变量只会显示空字符串。
您可以简单地使用:
{{ $variable ?? '' }}
但是,如果您想将此行为设置为所有变量的默认行为,而不显式使用
??
运算符,您应该编写刀片编译器。
namespace App\Extensions;
use Illuminate\View\Compilers\BladeCompiler;
class CustomBladeCompiler extends BladeCompiler
{
protected function compileEchoDefaults($value)
{
return preg_replace('/\{\{\s*(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\}/', '{{ $1 ?? \'\' }}', $value);
}
public function compileString($value)
{
$value = $this->compileEchoDefaults($value);
return parent::compileString($value);
}
}
use App\Extensions\CustomBladeCompiler;
public function register()
{
$this->app->singleton('blade.compiler', function () {
return new CustomBladeCompiler($this->app['files'], $this->app['config']['view.compiled']);
});
}