view.latte

This is the file that we use to build the front end and show the data from the fields defined in model.json and then populated in the admin screen.

Gutenberg has two ways of rendering blocks on the front end: via PHP and via JS. Our primary way of handling this is via PHP, or more specifically via the latte templating engine from the view.latte file.

There are scenarios where you’d want to do it via JS. If that’s the case, you would use the view.js file. Read more about those scenarios on the view.js page.

We suggest reading the model.json and controller.php pages before continuing

Rendering the block on the front-end

Let’s say that we’ve defined 3 fields in our model.json file:

  • title – rich text field
  • text – regular text field
  • button – CTA component field

The part of the code responsible for defining these fields in model.json would look like this.

[block-dir]/model.json...
"title": {
  "type": "object",
  "field_meta": {
    "type": "text",
    "variation": "rich",
    "label": "Title"
  },
  "default": {
    "text": ""
  }
},
"text": {
  "type": "object",
  "field_meta": {
    "type": "text",
    "label": "Text"
  },
  "default": {
    "text": ""
  }
},
"button": {
  "type": "object",
  "field_meta": {
    "type": "cta",
    "label": "Button"
  },
  "default": {
    "title": "",
    "url": "",
    "target": false
  }
},
...

To show the values of these fields on the front-end, this is how we might write our view.latte code.

[block-dir]/view.latte<section class="some-section-class">
  <h1 n:ifcontent>
    {$title['text']|noescape}
  </h1>
  <p n:ifcontent>
    {$text['text']}
  </p>
  {tr_a($button, "btn btn--brand")}
</div>

For the h1 and p tags, we are using latte’s n:ifcontent that will just not render anything if the fields are undefined or their values empty.

The h1 tag also uses latte’s filter |noescape. Since our title field is a RichText that allows formatting such as bolding, inserting links, etc, we must use the |noescape to properly render the HTML for all that formatting.

The button field (CTA component), is handled a bit differently. See how we are not using anything similar to n:ifcontent to check if this field is properly populated. We are using the tr_a helper function to do all this, and more for us.

Join Our Newsletter

To get updates about Theme Redone