0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelで変数をJavaScriptに渡す

Posted at

一番外側のレイアウトの役割を持ったbladeファイルにwindow.Laravelとグローバルに定義をする

そして他のビューや子のビューでレンダリングできるようにscriptsという名前でスタックを作っておく(@stack('scripts'))。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<script>
  window.Laravel = window.Laravel || {};
</script>
@stack('scripts')

<body>
  @yield('content')
</body>
</html>

そして子のビューなどでJSへ変数を渡したい場合があるときは、@pushディレクティブに@stackディレクティブに使った名前を使用して変数を代入します。これでJS側で変数を使うことができます

// $greeting = 'Hello world!';

@push('scripts')
    <script>
        window.Laravel.greeting = $greeting;
    </script>
@endpush

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?