将布尔值传递给 Laravel 中的视图

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

Pass a boolean to a view in Laravel

phplaravellaravel-4

提问by Lucien Dubois

What I try to do:

我尝试做的事情:

I try to pass a boolean to my view to to check if it is true or not. If it is set to true, I want to add a class. I use Laravel. Actually, here is my situation:

我尝试将一个布尔值传递给我的视图以检查它是否为真。如果设置为true,我想添加一个类。我使用 Laravel。其实我的情况是这样的:

  • The .red class is added to all rows
  • $finances->depense always return 1 even if it says 0 in the database
  • .red 类被添加到所有行
  • $finances->depense 总是返回 1,即使它在数据库中显示为 0

Here is my code:

这是我的代码:

index.blade.php

index.blade.php

@foreach($finances as $finance)
    @if ($finance->depense = 1)
        <tr class="red">
    @elseif ($finance->depense = 0) 
        <tr>
    @endif
            <td><a href="{{ URL::to('finances/' . $finance->id) }}">{{$finance->description}}</a></td>
            <td>{{ $finance->depense }}</td>
            <td>{{ $finance->prix }}</td>
            <td>{{ $finance->tps }}</td>
            <td>{{ $finance->tvq }}</td>
            <td>{{ $finance->grandtotal }}</td>
        </tr>
@endforeach

FinancesController.php

财务控制器.php

public function index()
{
    $finances = Finance::all();
    return View::make('finances.index')->withFinances($finances);
}

What is wrong?

怎么了?

回答by Lucien Dubois

The answer was finally very simple..

答案终于很简单了..

Instead of

代替

@if ($finance->depense = 1)
    <tr class="red">
@elseif ($finance->depense = 0) 
    <tr>
@endif

I changed the expression from =(Assignment Operator)to ==(Equal)

我将表达式从(Assignment Operator)更改为(Equal)===

@if ($finance->depense == 1)
    <tr class="red">
@else 
    <tr>
@endif

Don't forget to use double equal to compare.

不要忘记使用 double 等于进行比较。

回答by undefined variable

I could be wrong but I thought you don't need to do comparison with boolean value for a condition check, as it defaults to true.

我可能是错的,但我认为您不需要与布尔值进行比较以进行条件检查,因为它默认为 true。

@if ($finance->depense)
    <tr class="red">
@else 
    <tr>
@endif

If you want to check for false add the '!'

如果您想检查错误,请添加“!”

@if (!$finance->depense)
    <tr class="red">
@else 
    <tr>
@endif