【问题标题】:How to check if page property exists in OctoberCMS layout template如何检查 OctoberCMS 布局模板中是否存在页面属性
【发布时间】:2018-11-09 09:28:46
【问题描述】:

在布局中,当页面未定义属性时,使用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 部分会抛出异常。

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

【问题讨论】:

    标签: twig octobercms


    【解决方案1】:

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

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

    这符合我的预期,但我不确定这是否是最佳解决方案。

    【讨论】:

    • 是的,它是正确和标准的解决方案,不用担心。
    【解决方案2】:

    我找到了一个比 my previous answer 更好的解决方案。

    使用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 %}
    

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 2018-02-15
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多