php Laravel Blade 通过@include 传递带有字符串的变量会导致错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29739745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:32:51  来源:igfitidea点击:

Laravel Blade passing variable with string through @include causes error

phplaravellaravel-5blade

提问by joeyfb

In Laravel 5.0.27 I am including a view with with a variable and the following code:

在 Laravel 5.0.27 中,我包含了一个带有变量和以下代码的视图:

@include('layouts.article', [
        'mainTitle' => "404, page not found",
        'mainContent' => "sorry, but the requested page does not exist :("
    ])

and I get the following error...

我收到以下错误...

FatalErrorException syntax ... error, unexpected ','

FatalErrorException 语法...错误,意外的“,”

I've narrowed down that the error is solely from the "(" in the "mainContent" variable string, and when I remove the "(" the error disappears and everything runs fine. I can't find anything in documentation on this or any similar errors listed online.

我已经缩小了错误仅来自“mainContent”变量字符串中的“(”,当我删除“(”时,错误消失并且一切正常。我在文档中找不到任何关于此或在线列出的任何类似错误。

Does anyone know if this is expected behavior or if this is a bug that should be reported?

有谁知道这是预期的行为还是应该报告的错误?

Thanks so much for your time!

非常感谢您的时间!

回答by joeyfb

It's not a bug but a limitation of blade syntax due to regex. Solution came from github:

由于正则表达式,这不是错误而是刀片语法的限制。解决方案来自github

The problem is using multi-line. You can only use a single line to [pass variables] in Blade, since syntax is limited [by regular expressions]

Try the code below and you should be good to go:

@include('layouts.article', ['mainTitle' => "404, page not found", 'mainContent' => "sorry, but the requested page does not exist :("])

问题是使用多行。您只能在 Blade 中使用一行来[传递变量],因为语法受到[正则表达式]的限制

试试下面的代码,你应该很高兴:

@include('layouts.article', ['mainTitle' => "404, page not found", 'mainContent' => "sorry, but the requested page does not exist :("])

回答by varun sharma

You can pass a $data array

你可以传递一个 $data 数组

<?php $data=[
        'mainTitle' => "404, page not found",
        'mainContent' => "sorry, but the requested page does not exist :("
    ]  ?>
@include('layouts.article', $data)

use $data['mainTitle']etc in layouts.article

使用$data['mainTitle']layouts.article

回答by Matteus Barbosa

In 5.8v, included views inherit all variables from the parent as per in documentation:

5.8v 中,包含的视图按照文档从父级继承所有变量:

Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

@include('view.name', ['some' => 'data'])

即使包含视图将继承父视图中可用的所有数据,您也可以将一组额外数据传递给包含视图:

@include('view.name', ['some' => 'data'])