How-to library · Developer docs

How-to library

Task-shaped pages: a title that starts with a verb, the situation in a few lines, the steps, the working code in both engines, and why this way rather than another. Found from a search, done, and left.

Add a layout area and render it in the template

Add the layout area to the layout in the admin with a permanent name, an input type and an editor-facing label; it appears empty on every record using the layout. Then read it with the getter for its type.

Context

Context. A layout area is a field on a layout. Adding one to a layout adds it, empty, to every record that uses the layout, and the template reads it by name. The name is the identity: content is stored against the layout area, and a rename keeps the content but breaks every template still asking for the old name. Choose it as you would a database column.

Steps

  1. Open the layout in the admin and add a layout area: name summary (lower camel case, named for what it holds), input type Textarea, label "Summary", help "One or two sentences shown in listings".
  2. Set required only if every record must have it; a required area blocks saving records that were fine yesterday.
  3. Save the layout. Existing records show the new empty field on their next edit.
  4. Read it in the template with the getter for its category: text with getAreaText(), rich text with getAreaHtml(), an image with getAreaImage().

Template code

Template code
{$summary = $page->getAreaText('summary')}
{if !empty($summary)}<p class="lead">{$summary|escape}</p>{/if}
{$page->getAreaHtml('body')}
{$photo = $page->getAreaImage('photo')}
{if !$photo->isBlank()}{$photo->getResized(800, 450, 'fit')->getHtml()}{/if}
{% set summary = page.getAreaText('summary') %}
{% if summary is not empty %}<p class="lead">{{ summary|e }}</p>{% endif %}
{{ page.getAreaHtml('body') }}
{% set photo = page.getAreaImage('photo') %}
{% if not photo.isBlank() %}{{ photo.getResized(800, 450, 'fit').getHtml() }}{% endif %}

Why this and not that

Not a custom field: pages, posts and other records with layouts take areas, and custom fields are for records that have none. Not a new area for every layout that needs the same thing: reuse the same name and input type across layouts, so a record switched from one layout to another keeps its content (content moves between same-named areas). Not the shorthand $page->summary inside an attribute or a comparison; that is for element content only.

Go deeper

Was this page helpful?

Your answer goes to the docs team.