【问题标题】:Passing variables through blade includes in Laravel通过刀片传递变量包含在 Laravel 中
【发布时间】:2019-08-05 17:01:58
【问题描述】:

我是 Laravel 的初学者,我正在练习将以前的(简单)网站转换为 Laravel。

基本上,我创建了一个具有 HTML 结构的模板,并使用 @includes@yield

更改了主要内容

html中有趣的部分template.blade.php是这样的

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<!-- Title -->
<title>@yield('title')</title>

....
....

<!-- CSS Customization -->
<link rel="stylesheet" href="/assets/css/custom.css">
@yield('css')

....
....

@include('include._header')
@include('include._test_script')
@include('include._footer')

....
....

<!-- JS Customization -->
<script src="/assets/js/custom.js"></script>
@yield('js')

路由器调用包含模板的test.blade.php。此刀片文件有一些自定义 php 代码,其中包含 $extra_script 变量

<?php $extra_script = " alert(0); console.log(0);";?>

@extends('layouts.template')

@section('css')
   ....
@endsection

@section('js')
    ...
    <script>
        {!! $extra_script !!}
    </script>
@endsection

加载此页面,脚本运行良好,我看到警报消息的内容为 0。

现在我正在尝试将 $extra_string 更新到 /include/test_script.blade.php 文件中,但它没有工作。

这个包含刀片文件是这样的:

 @php
     $extra_script = " alert(1); console.log(1);";
 @endphp

 or

 <?php $extra_script = " alert(1); console.log(1);"; ?>

结果没有错误,仍然显示 alert(0)。

我知道在刀片模板中但在控制器中包含 PHP 代码并不优雅,但这是一种快速且快速的移植,可以在一段时间内使网站上线。

如何在视图中修复它?

【问题讨论】:

    标签: php laravel laravel-blade


    【解决方案1】:

    我会说顺序不正确,首先test.blade.php 是从template.blade.php 扩展而来的。 template.blade.php@include('include._extra_script') 将警报设置为 1,但随着 test.blade.php 从该模板扩展,它会将 $extra_script 覆盖为警报 0 的那个。

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2021-03-09
      • 1970-01-01
      • 2020-06-07
      • 2022-01-01
      • 1970-01-01
      • 2022-11-11
      • 2022-11-02
      • 2020-04-03
      相关资源
      最近更新 更多