在布局中,使用is defined
检查页面属性会在页面未定义属性时产生类似"调用未定义的方法October\Rain\Halcyon\Builder::metadescription(("的错误。我希望测试为false,而不是抛出异常。
我有如下布局检查if this.page.meta_description is defined
。
description = "Default layout"
==
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ this.page.title }}</title>
{% if this.page.meta_description is defined and this.page.meta_description is not empty %}
<meta name="description" content="{{ this.page.meta_description }}">
{% endif %}
</head>
<body>
...
</body>
</html>
如果使用此布局的页面定义了meta_description
属性,则其呈现良好。然而,若页面并没有定义它,this.page.meta_description is defined
部分会抛出异常。
检查是否定义了页面属性的正确方法是什么?
我刚刚找到了一种解决这种情况的方法,通过关联数组语法访问属性。
{% if this.page['meta_description'] is defined and this.page['meta_description'] is not empty %}
<meta name="description" content="{{ this.page.meta_description }}">
{% endif %}
这正如我所期望的那样有效,但是,我不确定这是否是最好的解决方案。
我找到了一个比以前的答案稍微好一点的解决方案。
使用Page.__isset()
方法检查是否定义了特性。
{% if this.page.__isset('meta_description') and this.page.meta_description is not empty %}
<meta name="description" content="{{ this.page.meta_description }}">
{% endif %}
我认为这更好的原因是它也可以与ViewBag组件一起使用。
我在使用具有ViewBag属性的is defined
时遇到了同样的问题。然而,阵列访问解决方案无法与ViewBag配合使用。为了避免混淆,我将对Page对象和ViewBag组件使用__isset()
方法。
注意:如果您在布局中使用ViewBag,还应该检查ViewBag是否存在,因为并非所有页面都实例化ViewBag组件。
{% if viewBag is defined and viewBag.__isset('canonical_url') and viewBag.canonical_url is not empty %}