Template inheritance and block composition: preserving design freedom

Two pages in one Symfony Demo with explicit Twig inputs and three collection states. Verified with 14 methods, 65 assertions, and a controlled fragment change.

A shared structure leaves room for different compositions.

A journal homepage opens with an author's introduction, while a workshop page starts with a list of supplies. Both show a collection of notes and share the same navigation. The temptation is clear: build one large template and add show_intro, show_tools, and show_cards parameters. A few changes later, that template dictates what every page is allowed to be, although its original purpose was simply to remove repetition.

It helps to separate two decisions. Inheritance preserves the common document structure. Composition determines which content blocks appear on a particular page and in what order. Shared navigation and a footer can then coexist with pages that tell different stories.

Consider an independent teaching example for Symfony 8.1, PHP 8.4.1+, and Twig 3: a reading room and a map workshop within one application. Templates and synthetic data are integrated into the single Demo. On PHP 8.5.12, 14 test methods passed with 65 assertions, and the kernel returned six HTML responses covering two pages in three states.

The shell should know less than the page

A shared shell needs the document title, navigation, a place for the main content, and a footer. It does not need to know whether today's visitor is choosing a note or preparing tools for drawing a map. Those differences belong to the page templates.

In the example, the existing base.html.twig owns the HTML document. A new page_composition/layout.html.twig extends it and adds a common header, main, and footer for the two teaching routes. Inside main, one page_blocks slot is available. Each page fills that slot with its own composition. Other application routes continue using their own templates.

These are three levels with different reasons to change: document, section shell, and individual page. A similar separation is described in the Symfony template documentation. The number of levels is not a goal: a small page can extend the base document without an intermediate layout. An extra level is justified by shared responsibility, not by a desire for matching directory structures.

In this section, the shell creates the first-level heading from an explicitly supplied title. Blocks use their own lower-level headings. This particular agreement prevents accidental duplication of H1 when two ready-made sections are combined on one page. Another design may assign the heading to a different owner, but that owner needs to be clear.

The page chooses the order

The reading room contains an introduction and a collection. Its entire template is short:

{% extends 'page_composition/layout.html.twig' %}

{% block page_blocks %}
    {% include 'page_composition/blocks/intro.html.twig' with {text: intro} only %}
    {% include 'page_composition/blocks/cards.html.twig' with {
        heading: 'Нотатки для читання', list: cards
    } only %}
{% endblock %}

In the same slot, the map workshop includes a supplies block first, followed by the same collection under a different heading. It has no introduction. Adding one later should change that page's composition; the shell and the reading-room template should not acquire a new flag.

The Twig block name page_blocks marks an override point in the inheritance chain. The collection's content block is a separate fragment brought in through include. Both are often called blocks, but they solve different problems. One lets the page fill a place in its parent template; the other gives it a ready-made composition element. The override mechanism is explained in Twig extends.

For two known pages, explicit includes are simpler than a universal registry. If an editor starts choosing the order, a different task emerges: a validated set of block types, a schema for their parameters, and rules for permitted combinations. There is no need to accept an arbitrary Twig filename from an HTTP request. In the teaching controller, page template names are fixed in code, while a route parameter merely selects one of three synthetic data states.

A small fragment still has a contract

The collection receives two arguments: heading and list. The latter contains state and a list of cards. A card holds plain-text title and summary; it knows nothing about the page name, current route, or navigation placement. The fragment does not query a data repository or decide which articles a reader may access. It displays an already prepared result.

The only keyword restricts passing the current context to the included template. The explanation and its with_context: false equivalent appear in the Twig include documentation. This makes the fragment's inputs easier to see and allows reuse on a page that lacks incidental variables from the first caller.

This is a template dependency boundary, not an authorization system. Globals, functions, and extensions registered with Twig require their own discipline. The word only does not turn an arbitrary third-party template into safe code or replace a sandbox. All templates in this example are application-owned; the visitor only chooses an allowed teaching scenario.

A predictable input also reduces the need for default beside every field. A missing required list is a page assembly error. A valid list with no cards is a normal collection state. Silently replacing both cases with [] would make incorrect wiring look like a successful empty result.

An empty collection and an unavailable source

The CardList model permits three states:

State Data Message for the reader
ready A nonempty list of cards Show the cards
empty An empty list There are no notes in this collection yet
unavailable An empty list The collection is temporarily unavailable

The model constructor rejects contradictory combinations. For example, ready without cards or unavailable with cards is invalid. This is not a universal model for every list: a stale but permitted cached result would need a separate meaning. Adding it to this example without a need would be unnecessary.

View preparation maps only a known source failure to unavailable:

public function forScenario(string $scenario): CardList
{
    try {
        $cards = $this->source->read($scenario);
    } catch (CardsUnavailable) {
        return new CardList('unavailable', []);
    }

    return new CardList($cards === [] ? 'empty' : 'ready', $cards);
}

Rendering happens later in the controller, outside this try. A template syntax error or a missing required argument should therefore not become a message about a temporarily unavailable collection. Likewise, an unexpected LogicException from the source propagates: it is not part of the agreed failure state.

On both teaching pages, the collection is an additional section. If it is unavailable, the introduction or supplies list remains useful; the chosen page policy is HTTP 200 with an explicit message inside the section. A request for a page whose entire content depends on that unavailable source would require a different response-status decision. Composition does not establish a universal HTTP error policy on its own.

The template displays the state without guessing

The collection fragment has its own heading and rendering branches. Its central portion looks like this:

{% if list.state == 'unavailable' %}
    <p data-message="unavailable">Добірка тимчасово недоступна. Спробуйте пізніше.</p>
{% elseif list.state == 'empty' %}
    <p data-message="empty">У цій добірці поки немає нотаток.</p>
{% else %}
    <ul>
        {% for card in list.cards %}
            <li data-card>
                <h3>{{ card.title }}</h3>
                <p>{{ card.summary }}</p>
            </li>
        {% endfor %}
    </ul>
{% endif %}

An empty result does not hide the section heading: the reader can see what was supposed to occupy that space. This is a choice made for the example. A product may sometimes omit an optional section entirely, but that decision should be explicit. Otherwise, a designer cannot distinguish planned absence from broken wiring.

The synthetic card titled <b>Мапа</b> & олівець exists to check escaping. Its title must remain text, with no <b> element in the DOM. There is no raw here; automatic escaping and the strict_variables option are documented in Twig for developers. In the test environment, strict variables helps detect a missing required argument.

Escaping HTML text does not solve every presentation security concern. If cards received arbitrary URLs, their allowed schemes and origins would need a separate policy. Rich text would require its own sanitization contract. For now, the fragment accepts ordinary strings and promises no broader behaviour.

What should survive a change to one block

A useful composition check starts with a change that a page actually needs. For example, reverse the order of a card's heading and description, or give the card a new presentation. Both pages should use the updated fragment, while their headers, footers, titles, and other section ordering remain intact.

This does not mean a shared fragment must never differ between pages. If the reading room needs an editorial preview and the workshop needs a technical table, two separate views of the same data may be appropriate. Packing both purposes into a dozen flags would reproduce the original problem one level lower.

Copying the entire layout for a different card, meanwhile, creates new owners for navigation and the footer. Before taking that step, ask what actually changed: the data, one fragment, the order of sections, or the whole shell. The size of the change helps identify the right reuse boundary.

Check composition through its result

The prepared suite contains 14 test methods: eight HTTP methods, four covering the model and view preparation, and two for the isolated Twig fragment. All 14 methods passed with 65 assertions. The HTTP layer uses Symfony WebTestCase to inspect the route, status, and resulting DOM through the kernel.

Positive scenarios should observe different section sequences: intro → cards and tools → cards. A separate check compares the header and footer and requires one main and one H1. Both pages are checked for empty and unavailable states, absence of cards, and the correct message. Another check looks for the literal title with angle brackets and the absence of a generated HTML element.

Isolated Twig rendering should work with only the two documented arguments. Omitting list should produce an error. Data-preparation checks should distinguish a known source refusal from an unexpected exception, while the model should reject a contradictory state. A route with an unknown scenario should return 404; POST to the reading page should return 405.

A controlled change to the cards fragment alone added a class to card headings on both ready pages. Complete HTML responses differed only by that expected replacement; after restoration, all six responses and the fragment matched the baseline byte for byte. This kernel experiment confirms specific HTML behavior, but not responsiveness, speed, or usability: no browser check was performed.

Design freedom survives when a difference has a clear owner. The shell holds the page's shared structure, a fragment fulfils a small presentation contract, and the page itself determines their sequence. The next change can then begin in a specific place, without rewriting the whole document or teaching the base template every product detail.

  1. Symfony Core Entity or DTO: which data should a page receive from storage?
  2. Symfony Core The first useful page after the Symfony skeleton: a catalogue of learning notes
  3. Symfony Core Errors, empty results and missing records: three application responses
  4. Architecture Configuration or a new implementation: when to stop adding settings