如何检查页面 属性 是否存在于 OctoberCMS 布局模板中
How to check if page property exists in OctoberCMS layout template
在布局中,当页面未定义 属性 时,用 is defined
检查页面 属性 会产生类似 "Call to undefined method October\Rain\Halcyon\Builder::meta_description()" 的错误。
我希望测试是假的而不是抛出异常。
我有如下布局检查 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 组件一起使用。
我在使用 is defined
和 ViewBag 属性 时遇到了同样的问题。但是,数组访问解决方案不适用于 ViewBag。
为避免混淆,我会对 Page 对象和 ViewBag 组件使用 __isset()
方法。
注意:如果您在布局中使用了ViewBag,您还应该检查viewBag是否存在,因为并非所有页面都会实例化ViewBag组件。
{% if viewBag is defined and viewBag.__isset('canonical_url') and viewBag.canonical_url is not empty %}
在布局中,当页面未定义 属性 时,用 is defined
检查页面 属性 会产生类似 "Call to undefined method October\Rain\Halcyon\Builder::meta_description()" 的错误。
我希望测试是假的而不是抛出异常。
我有如下布局检查 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 组件一起使用。
我在使用 is defined
和 ViewBag 属性 时遇到了同样的问题。但是,数组访问解决方案不适用于 ViewBag。
为避免混淆,我会对 Page 对象和 ViewBag 组件使用 __isset()
方法。
注意:如果您在布局中使用了ViewBag,您还应该检查viewBag是否存在,因为并非所有页面都会实例化ViewBag组件。
{% if viewBag is defined and viewBag.__isset('canonical_url') and viewBag.canonical_url is not empty %}