【问题标题】:Is there a way to place switch in include?有没有办法在包含中放置开关?
【发布时间】:2018-06-25 15:03:44
【问题描述】:

我正在开发基于 Laravel 5.4 框架的 PHP 项目。我想知道是否有办法将 switch 语句放入包含调用中。

我正在尝试做这样的事情:

@include('components/notification_message/_notification_message_html'
        , [ 'notificationType' => $notificationType
          , 'notificationMessage' => $notificationMessage
          , 'iconType' => switch($notificationType){case 'success': 'check'; break; case 'warning': 'warning'; break; default: 'exclamation';break;}])

如您所料,我在尝试运行它后遇到了语法错误。 知道我应该怎么做吗?

【问题讨论】:

  • 也许你想在每个里面使用@if@elseif@elseif@else@endif@include。最简单的解决方案。每个人只要浏览一下代码就会明白。
  • 为什么不把开关放在components/notification_message/_notification_message_html
  • 这两个想法都很好,我已经尝试过并且奏效了。但我试图找到一些花哨的东西。如果没有其他人有更好的主意,我会将您的答案标记为好。
  • 一堆?: 可能是例如$notificationType === 'success' ? 'check' : ($notificationType === 'warning' ? 'warning' : ...)
  • 是的。这就是我一直在寻找的。谢谢!

标签: php laravel switch-statement laravel-blade


【解决方案1】:

你不能像这样使用 switch 语句。您可以改用ternary operator

@include('components/notification_message/_notification_message_html', [
    'notificationType' => $notificationType,
    'notificationMessage' => $notificationMessage,
    'iconType' => $notificationType === 'success' ? 'check' : ($notificationType === 'warning' ? 'warning' : 'exclamation')
]);

【讨论】:

  • 谢谢。这就是我一直在寻找的。​​span>
【解决方案2】:

无法在包含中放置 switch 语句。您可以使用包含进行直接切换:

@switch($i)
    @case(1)
        @include('...');
        @break

    @case(2)
        @include('...');
        @break

    @default
        @include('...');
@endswitch

或者您可以使用@if 指令和/或includeIfincludeWhen 的某种组合:

@includeIf('view.name', ['some' => 'data'])

@includeWhen($boolean, 'view.name', ['some' => 'data'])

https://laravel.com/docs/5.6/blade#including-sub-views

【讨论】:

    猜你喜欢
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2020-08-24
    • 2010-12-09
    • 2020-11-30
    • 2013-04-06
    相关资源
    最近更新 更多