在 laravel-blade 中生成动态 css 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35350344/
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
Generate dynamic css classes in laravel-blade
提问by mrhn
I'm in a classical scenario where i want based on wheter an error has occurred or not to change the css classes. As shown below, where has-error should change accordingly.
我处于经典场景中,我希望根据是否发生错误来更改 css 类。如下所示,其中 has-error 应相应更改。
<div class="form-group has-error">
The project is in Laravel, where we mainly want to do everything in Blade
as of now, we came up with the following solution which works, but does not look pretty or intuitive at all, so the question is, is there a more optimal way of doing this?
该项目在 Laravel 中,到目前为止我们主要想在其中完成所有工作Blade
,我们提出了以下可行的解决方案,但看起来根本不漂亮或不直观,所以问题是,是否有更优化的方法这样做?
<div class="form-group
@if($errors->has('email'))
has-error
@endif
">
回答by Jilson Thomas
Try the if else condition short hand code:
试试 if else 条件简写代码:
<form class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
This seems neat.
这看起来很整洁。
Even the Laravel 5.2 auth forms are done this way.
甚至 Laravel 5.2 auth 表单也是这样完成的。
回答by Wistar
That's what I do. You could also do it that way:
我就是做这个的。你也可以这样做:
@if($errors->has('email'))
<div class="form-group has-error">
//You can also edit classes of other elements
</div>
@else
<div class="form-group"></div>
@endif
回答by Francis
You can make use of arrays to store the class names
您可以使用数组来存储类名
@php
$formGroupClasses = ['form-group'];
if ($errors->has('email')) {
$formGroupClasses[] = 'has-error';
}
@endphp
and then implode them to create a string
然后内爆它们以创建一个字符串
<form class="{{ implode(' ', $formGroupClasses) }}">