Laravel Blade: What is best practice for adding javascript in blade files?

两盒软妹~` 提交于 2021-01-21 05:14:26

问题


I inherited a Laravel project that has many blade files with javascript inside tags within the blade file. The issue is that there is a lot of repetitive JS logic so I'd like to extract the JS and create JS files to include in the blade? Example: <script src="{{ asset('js/components/file.js')}}"></script> Is this the best practice for blade files or is it expected to be have the JS within the actual file?


回答1:


First you have to assign where yo want to push scripts in your layout. for example, say layout.blade.php is your main layout file and you want to inject codes after footer. So add

@stack('scripts')

after footer.

Now in your blade file, use @push to inject your code.

@push('scripts')
<script>
// your code
</script>
@endpush

check blade stack for further detail.




回答2:


I recommend you to maintain a specific section for page-specific javascript.

Please refer the following examples..

Example template.blade.php

  <body>

    @yield('content')

    @include('_partial.scripts')

    @yield('page-script')

    @include('_partial.footer')

</body>

then

@section('page-script')
<script type="text/javascript">
    // your custom script
</script>
@stop


来源:https://stackoverflow.com/questions/55757395/laravel-blade-what-is-best-practice-for-adding-javascript-in-blade-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!