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 is defined.

description = "Default layout"

<!DOCTYPE html>
        <meta charset="utf-8">
        <title>{{ }}</title>
    {% if is defined and is not empty %}
          <meta name="description" content="{{ }}">
    {% endif %}

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

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



I found a slightly better solution than my previous answer.

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

{% if'meta_description') and is not empty %}
  <meta name="description" content="{{ }}">
{% 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 %}