Toastr 使用 Laravel 会话变量作为警报消息

Toastr to use Laravel session variables as alert messages

我想从 Bootstrap 警报切换到 Toastr 警报。我目前的工作设置是:

@if (Session::has('flash_notification.message'))

     <div class="alert alert-{{ Session::get('flash_notification.level') }}">
         <button type="button" class="close" data-dismiss="alert" 
             aria-hidden="true">&times;</button>
         {{ Session::get('flash_notification.message') }}
     </div>

 @endif

但我现在正在努力在 JS 中访问 Laravel 的会话变量。

实际的JS工作示例是:

$(document).ready(function() {

    toastr.info('Page Loaded!');

    });

});

但是,我想使用 Laravel 的会话变量来包含不同的消息和警告框:

@if (Session::has('flash_notification.message'))

    <script>
        $(document).ready(function() {

            toastr.options.timeOut = 4000;
            toastr.{{ Session::get('flash_notification.level') }}('{{ Session::get('flash_notification.message) }}');

        });
    </script>

@endif

我遇到了各种错误,例如 unexpected ;。任何帮助将不胜感激。非常感谢。

由于您在 blade-template 中工作,您可以使用 {{ var/function() }} 输出 variable/function 的内容。如果你想要未转义的输出,你可以使用 {!! var/function() !!}.

所以你的问题的解决方案是,你需要用 {{ }} 标签包围你的 php 代码:

@if (Session::has('flash_notification.message'))

    <script>
        $(document).ready(function() {

        toastr.{{ Session::get('flash_notification.level') }}
        ('{{ Session::get('flash_notification.message') }}');

        });
    </script>

@endif