List of fields in a page?

I feel like I’m overlooking something, but I’m trying to get an array of the fields in my page to iterate over.

In my blueprint for the page I have this:

title: Page
pages: true
files: true
fields:
  title:
    label: Title
    type:  text
  housestyleimage:
    label: Housestyle Image
    type:  text
  housestyle:
    label: House Style
    type:  textarea
  logos:
    label: Logos
    type: textarea
  color:
    label: Color
    type: textarea
  fonts:
    label: Fonts
    type: textarea

I was hoping I could do something like $page->fields() to get an array of the fields, but this doesn’t seem to be the case. What would be the best way to get an array of all the field’s labels?

This a solution from an older post:

<?php
$c = $page->content();
foreach ($c as $key => $value) {
  if ($key == "fields") {
    foreach ($value as $field) {
      echo $field . ": " . $page->$field() . "<br/>";
    }
  }
}
?>

Not tested, though.

<?php
  $c = $page->content();
  foreach ($c as $key => $value) {
    if ($key == "fields") {
      echo "<dl>";
      foreach ($value as $field) {
        echo "<dt>" . $field . "</dt><dd>" . $page->$field() . "</dd>";
      }
      echo "</dl>";
    }
  }

Awesome! Thanks guys.

$page->content()->toArray() will also give you a standard array which may be easier to work with in some circumstances.

@SQBiz Thanks, I knew there was a cleaner solution, just couldn’t find it.

@SQBiz, ah that’s really nice!

I thought this would solve it for me, but I actually want to access the label that’s in the blueprint (in my example above those would be Title, Housestyle Image, Logos, Color, Fonts). Is there any way to get to that?

The label of the field only exists for display in the panel, it cannot be accessed via template (or not that I know of). As a workaround, you could probably map your fields and labels in your config file, or if you are on a multi language site, in your language files, and then access those variables in your template.