laravel - 如何在编译后的视图文件中执行 javascript(使用 View::render 方法)
问题描述
是否可以从编译视图执行 javascript 代码?我需要在我的 index.blade 文件中编写一些 js 代码来处理一些事件。我尝试了 3 种方法,但它们都不起作用。
控制器。
$advertisements = Advertisement::get();
$view = View::make('test::admin/index',['advertisements'=> $advertisements]);
$html = $view->render();
return $html;
index.blade.php
@push('stackscript') // NOT WORKING
<script>
alert();
</script>
@endpush
<script> // NOT WORKING
alert();
</script>
@section('footer_script') // NOT WORKING
<script>
alert();
</script>
@endsection
<div class="row">
@foreach ($advertisements as $advertisement)
<div class="col-md-9">
<div>{{ $advertisement->title }}</div>
<div>{{ $advertisement->body }}</div>
<div><img src="{{asset($advertisement->image)}}"></div>
</div>
<div class="col-md-3">
<form id="plugin-advertisement" method="POST" action="{{route('plugin.delete-advertisement', $advertisement->id)}}">
@csrf
@method("DELETE")
<button class="btn bnt-sm btn-outline-danger">delete</button>
</form>
</div>
@endforeach
</div>
Vue 组件
window.axios.get(this.url)
.then((res) => {
this.pluginPanel = res.data;
});
template:
<div v-if="!loading" v-html="div(pluginPanel)" />
解决方案
您的所有三种方式都需要一个具有核心 HTML 的布局文件。
布局文件master.blade.php
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content="{{ csrf_token() }}" />
<title>Test to render JavaScript</title>
</head>
<body>
@stack('stackscript') //You render JavaScript - first way
@yield('footer_script') //You render JavaScript - third way
</body>
</html>
在index.blade.php
中,您应该编写如下代码。
<!-- resources/views/layouts/app.blade.php -->
@extends('layouts.master')//You must have this line to extend layout.
@push('stackscript') //I hope this script will run
<script>
alert();
</script>
@endpush
<script> //I hope this script will run
alert();
</script>
@section('footer_script') //I hope this script will run
<script>
alert();
</script>
@endsection
<div class="row">
@foreach ($advertisements as $advertisement)
<div class="col-md-9">
<div>{{ $advertisement->title }}</div>
<div>{{ $advertisement->body }}</div>
<div><img src="{{asset($advertisement->image)}}"></div>
</div>
<div class="col-md-3">
<form id="plugin-advertisement" method="POST" action="{{route('plugin.delete-advertisement', $advertisement->id)}}">
@csrf
@method("DELETE")
<button class="btn bnt-sm btn-outline-danger">delete</button>
</form>
</div>
@endforeach
</div>
推荐阅读
- python - TensorFlow Object Detection API Mask-RCNN 训练导致OOM错误
- webrtc - WebRtc 流而不损失质量
- java - java ee 使用 Morphia 时如何防止没有 sql 注入?
- python - 如何使用 python ISBNLIB 元方法捕获错误并继续
- python - 将 BDP 公式转换为 tia
- html - cakephp 3.6 中的 'type'=> 'datetime-local'
- arrays - 我的 for 循环找不到我的数组,尽管我指定了它
- javascript - 没有管道 Angular 6 的过滤器:最重要的问题
- ruby-on-rails - 资产在服务器中预编译但不显示在 puma 和 nginx 服务器中
- ssl - 如何执行 EV ssl 认证的验证流程