首页 > 解决方案 > 如何检查 OctoberCMS 布局模板中是否存在页面属性

问题描述

is defined在布局中,当页面未定义属性时,检查页面属性会产生类似“调用未定义方法 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部分会抛出异常。

检查页面属性是否已定义的正确方法是什么?

标签: twigoctobercms

解决方案


我刚刚找到了一种通过关联数组语法访问属性来解决这种情况的方法。

{% if this.page['meta_description'] is defined and this.page['meta_description'] is not empty %}
  <meta name="description" content="{{ this.page.meta_description }}">
{% endif %}

这按我的预期工作,但是,我不确定这是否是最好的解决方案。


推荐阅读