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
How to know if a variable is set in the view
提问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 $errors
variable 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 $errors
in 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 $errors
variable that is returned by the validator
class? 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 true
in Laravel 4.
简单的检查if( isset($errors))
总是会true
在 Laravel 4 中返回。
回答by jairobg
You are using blade Code:
您正在使用刀片代码:
@if($var)
--php code--
@endif
回答by jairobg
回答by Moeed Farooqui
if(isset($errors) && !empty($errors)){
// your code here
}