laravel DOMPDF loadView() 错误 - 未定义变量:数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28216993/
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-09-14 10:47:11  来源:igfitidea点击:

DOMPDF loadView() error - undefined variable: data

phplaraveldompdf

提问by cchapman

I'm currently trying to incorporate the DOMPDF Wrapper for Laravelinto my project, however I'm having troble figuring out how to pass a variable into the PDF template.

我目前正在尝试将LaravelDOMPDF Wrapper 合并到我的项目中,但是我在弄清楚如何将变量传递到 PDF 模板时遇到了麻烦。

As per the instructions, in my controller I have:

按照说明,在我的控制器中,我有:

//PrintController.php
$data = array('name'=>'John Smith', 'date'=>'1/29/15');

$pdf = PDF::loadView('contract', $data);
return $pdf->stream('temp.pdf');

and in my view:

在我看来:

//contract.php
...
<p><?php echo $data->name ?><p>
<p>Signature</p>

But when I try to render the page, I get the error:

但是当我尝试渲染页面时,出现错误:

ErrorException (E_UNKNOWN) 
Undefined variable: data

I'm not sure why the loadView()method is not passing the $datavariable to the view. Is there a step I'm missing in setting it up in the controller and/or view?

我不确定为什么该loadView()方法没有将$data变量传递给视图。我在控制器和/或视图中设置它时是否缺少一个步骤?

回答by StephenMtl

The loadView method you are using is going to use the extract method before passing the data to the views. This method extracts all the array elements, and creates variables for them based on the key of the element

您正在使用的 loadView 方法将在将数据传递给视图之前使用提取方法。此方法提取所有数组元素,并根据元素的键为它们创建变量

This means that your array keys are going to be your variable names, ie $name and not $data->name. This is fairly standard in laravel, for example when using Blade Views.

这意味着您的数组键将是您的变量名,即 $name 而不是 $data->name。这在 Laravel 中是相当标准的,例如在使用 Blade Views 时。

http://php.net/manual/en/function.extract.php

http://php.net/manual/en/function.extract.php

回答by RANJITH

Use compact('data')instead of $data.

使用compact('data')代替$data

Example:

例子:

$pdf = \PDF::loadView('productType.invoice', compact('data'));