Ad

How To Check If Page Property Exists In OctoberCMS Layout Template

- 1 answer

In layout, checking page property with is defined produces an error like "Call to undefined method October\Rain\Halcyon\Builder::meta_description()", when page does not define the property. I expect the test to be false instead of throwing an exception.

I have layout like below checking 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>

If the page using this layout defines meta_description property, it renders fine. However, if the page does not define it, this.page.meta_description is defined part throws exception.

What is the proper way to check if a page property is defined or not?

Ad

Answer

I found a slightly better solution than my previous answer.

Use Page.__isset() method to check if a property is defined.

{% if this.page.__isset('meta_description') and this.page.meta_description is not empty %}
  <meta name="description" content="{{ this.page.meta_description }}">
{% endif %}

The reason why I think this is a bit better is that this can be used with ViewBag component as well.

I encountered the same problem using is defined with ViewBag property. However, array access solution didn't work with ViewBag. To avoid confusion, I would use __isset() method for both Page objects and ViewBag component.

Note: If you are using ViewBag in layout, you should also check if viewBag exists because not all pages instantiate ViewBag component.

{% if viewBag is defined and viewBag.__isset('canonical_url') and viewBag.canonical_url is not empty %}
Ad
source: stackoverflow.com
Ad