有没有办法在include中放置开关?

时间:2018-06-25 15:03:45

标签: php laravel switch-statement laravel-blade

我正在基于Laravel 5.4框架构建PHP项目。我想知道是否可以将switch语句放入include调用中。

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

@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;}])

您可以猜到,尝试运行它后出现语法错误。 知道我该怎么做吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

无法在包含文件中放置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

相关问题