Laravel - 如何在刀片视图中尝试/捕获?

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

Laravel - How to a try/catch in blade view?

laravellaravel-4blade

提问by Wallace Maxters

I would like to create a way to compile in a view, the try/catch. How can I do this in Laravel?

我想创建一种在视图中编译的方法,即 try/catch。我怎样才能在 Laravel 中做到这一点?

Example:

例子:

@try
<div class="laravel test">
    {{ $user->name }}
</div>
@catch(Exception $e)
    {{ $e->getMessage() }}
@endtry

回答by Martin Bean

You should nothave try/catchblocks in your view. A view is exactly that: a representation of some data. That means you should not be doing any logic (such as exception handling). That belongs in the controller, once you've fetched data from model(s).

你应该不会try/catch块你的看法。视图正是这样:一些数据的表示。这意味着您不应该执行任何逻辑(例如异常处理)。一旦您从模型中获取数据,它就属于控制器。

If you're just wanting to display a default value in case a variable is undefined, you can use a standard PHP null coalescing operatorto display a default value:

如果您只想在未定义变量的情况下显示默认值,您可以使用标准的PHP 空合并运算符来显示默认值:

{{ $user->name ?? 'Name not set' }}

回答by areed

You are probably doing something wrong if you need a try..catchin your view. But that does not mean you should never do it. There are exceptions to every rule.

如果您需要 atry..catch在您看来,您可能做错了什么。但这并不意味着你永远不应该这样做。每条规则都有例外。

So anyway, here is the answer:

所以无论如何,这是答案:

Put raw PHP in your view by using <?php ?>or @php @endphptags. Then put your try..catchin the raw PHP.

使用<?php ?>@php @endphp标签将原始 PHP 放入您的视图中。然后把你try..catch的原始 PHP。

@php
    try {
        // Try something
    } catch (\Exception $e) {
        // Do something exceptional
    }
@endphp

回答by Benjamin Ini

while i agree with @areed that something is wrong if you have to use a try...catch, there are weird cases where a wrong approach can lead you down that path. One instance is using the same blade to house a paginate()and a get()response. Well, this might help a little.

虽然我同意@areed 的观点,即如果您必须使用 try...catch,就会出现问题,但在某些奇怪的情况下,错误的方法可能会导致您走上这条道路。一个实例是使用相同的刀片来容纳一个paginate()和一个get()响应。嗯,这可能会有所帮助。

<?php try{ ?> 
    //try to show something
    {{ $products->links() }}
<?php }catch(\Exception $e){ ?>
    // show something else
<?php } ?>