php 如何知道是否在视图中设置了变量

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

How to know if a variable is set in the view

phplaravellaravel-4

提问by Israel Ortu?o

I'd like to know if there's a way to know if a variable exists in a view.

我想知道是否有办法知道视图中是否存在变量。

I'm creating a custom form's builder for my app theme and I'd like to include the $errorsvariable in a HTML tag. Any way to know if it's previously set in the view?

我正在为我的应用程序主题创建自定义表单的构建器,并且我想将该$errors变量包含在 HTML 标记中。有什么方法可以知道它以前是否在视图中设置过?

UpdateI meant how to access a view var outside the view. How to access the $errors var from somewhere else, a package for instance.

更新我的意思是如何访问视图外的视图变量。如何从其他地方访问 $errors var,例如一个包。

I'm currently creating a custom form builder:

我目前正在创建一个自定义表单构建器:

{{ MyFormBuilder::text('name', 'value', array()) }}

It should print

它应该打印

<input name="name" value="value" ... />
<p>ERRORS NAME REQUIRED</p>

The errors <p>tag only if an error found validating this field. I want to check from my text()function if there's an error in $errors.

<p>仅当发现验证此字段的错误时才使用错误标记。我想从我的text()函数中检查$errors.

I've tried using global $errorsin my function, but it does not work...

我试过global $errors在我的函数中使用,但它不起作用......

I hope it's a bit more clear ;)

我希望它更清楚一点;)

SolvedUsing Session::get('errors');;D Thanks to @machuga.

使用Session::get('errors');;D解决,感谢@machuga。

回答by Deepak Mallah

this should work

这应该有效

if(isset($var))

回答by Tim F

Are you talking to the $errorsvariable that is returned by the validatorclass? If so, don't bother with the extra code to check if it exists. From the L4 docs:

你是在和类$errors返回的变量说话validator吗?如果是这样,不要用额外的代码来检查它是否存在。来自 L4 文档:

Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that an $errors variable will always be available in all of your views, on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

Laravel 将始终检查会话数据中的错误,并在它们可用时自动将它们绑定到视图。因此,重要的是要注意 $errors 变量将始终在您的所有视图中可用,在每个请求中,允许您方便地假设 $errors 变量始终已定义并且可以安全使用。

Simply checking if( isset($errors))will always return truein Laravel 4.

简单的检查if( isset($errors))总是会true在 Laravel 4 中返回。

回答by jairobg

You are using blade Code:

您正在使用刀片代码:

@if($var)
  --php code--
@endif

回答by jairobg

You can use the PHP's in-built function isset()for that purpose.

isset()为此,您可以使用 PHP 的内置函数。

Code:

代码:

if( isset($errors) ){
//your code
}

Hope this helps!

希望这可以帮助!

回答by Moeed Farooqui

if(isset($errors) && !empty($errors)){
// your code here
}