{fragment}

A named part of the page that a request can ask for alone - for htmx and ajax swaps.

Layouts and components Tag pairs

Syntax

{fragment 'name'} ... {/fragment}

Parameters

name
The fragment's name, required. A request with &padFragment=name gets this part alone.

Description

{fragment 'name'} marks a part of the page. A normal request renders it in place, as if the tag were not there - which is what the examples below show. A request that names it - ?orders&padFragment=order-list, or a page whose PHP sets $padFragmentOnly = 'order-list' - gets that fragment's rendering and nothing else: the page renders up to the end of the fragment, which is then the whole response, bare and untidied; the rest of the page does not render. The first fragment of that name to finish is the one sent.

This is the server side of partial page updates: htmx (hx-get="?orders&padFragment=order-list") and {ajax 'orders', fragment='order-list'}. An htmx request that names no fragment asks for the one called like its target: with hx-target="#order-list" htmx sends HX-Target: order-list, and a page with a fragment of that name answers it alone. A page without one renders whole.

Keep conditions inside the fragment rather than around it: a fragment asked for that never rendered is an error under the strict check, and an empty 404 otherwise. A fragment without a name, or one that never closes, is an error under the strict check. The page cache never stores a fragment the PHP chose, since its key is the address.

Examples

Rendered in place

A normal request renders the fragment where it stands - the text around it shows too.

Templateexamples/fragment/1-in-place.pad
<h4>Open orders</h4>
{fragment 'fragmentOrders'}
  <ul id="fragmentOrders">{orders}<li>{$number}: {$customer}</li>{/orders}</ul>
{/fragment}
<p>Only <code>&amp;padFragment=fragmentOrders</code> would answer the list alone.</p>
PHPexamples/fragment/1-in-place.php
<?php

  $orders = [
    [ 'number' => 10416, 'customer' => 'Baane Mini Imports' ],
    [ 'number' => 10417, 'customer' => 'Euro+ Shopping'     ] ];

?>
Resultopen alone

Open orders

  • 10416: Baane Mini Imports
  • 10417: Euro+ Shopping

Only &padFragment=fragmentOrders would answer the list alone.

Swapped by htmx

The search field asks this page for the fragment named like its target; htmx swaps the answer in.

Templateexamples/fragment/2-htmx.src
<input type="search" name="q" hx-get="?orders" hx-trigger="keyup changed delay:300ms" hx-target="#order-list">
{fragment 'order-list'}
  <ul id="order-list">{orders}<li>{$number}: {$customer}</li>{/orders}</ul>
{/fragment}

See also

  • {ajax} Writes an empty div and a script that has the browser fetch another page into it after the page has loaded.
  • {live} A region of the page that re-renders on the server when something in it is clicked, submitted or changed, and swaps itself in.
  • {page} Renders another page of the application - its PHP and its template - in place of the tag.