` whose grid is
* laid out with CSS grid/flex. Email clients (Outlook especially) don't support those, so the grid
* collapses to a single stacked column. This renderer re-flows the already-rendered `
` items
* into an email-safe, table-based column layout — mirroring how the Gallery renderer arranges
* images (see {@see Gallery::build_gallery_table()}).
*
* The list items arrive already rendered (post-template is a dynamic block, so `$block_content`
* holds the final `
…
`), so this renderer never re-runs the query. Each item's
* image is extracted and rebuilt as a clean, responsive `` sitting directly in its grid cell —
* the same shape the Gallery renderer emits. This is deliberate: the images WordPress renders inside
* a post-template `
` are wrapped in fixed-width, auto-layout tables (`
`) that
* were never sized for email, and a nested `width: 100%` image inside them collapses to a few pixels
* in Gmail (the width has no resolvable basis). Hoisting the image into the grid cell gives it a
* definite basis so it fills its column and scales down on mobile. An item with no image falls back
* to its original markup untouched (text content stacks correctly on its own).
*/
class Post_Template extends Abstract_Block_Renderer {
/**
* Upper bound on grid columns, matching the maximum the core grid layout control allows (its
* Columns range control tops out at 16). Honors any column count an author can pick in the editor,
* while still bounding an out-of-range hand-edited value so it can't emit a runaway number of cells.
*/
private const MAX_COLUMNS = 16;
/**
* Per-cell padding (px) that stands in for the grid's `gap` between items.
*/
private const CELL_PADDING = 8;
/**
* Responsive image style applied to every rebuilt grid image. `width: 100%` fills the column,
* `max-width: 100%` lets it scale down on narrow viewports, and `height: auto` keeps the ratio.
* The explicit `width` attribute (set alongside this) is the Outlook fallback, since Outlook
* ignores `max-width`.
*/
private const IMAGE_STYLE = 'border: 0; line-height: 100%; width: 100%; max-width: 100%; height: auto; display: block;';
/**
* Renders the post-template block content using a table-based grid layout.
*
* @param string $block_content Block content.
* @param array $parsed_block Parsed block.
* @param Rendering_Context $rendering_context Rendering context.
* @return string
*/
protected function render_content( string $block_content, array $parsed_block, Rendering_Context $rendering_context ): string {
if ( '' === trim( $block_content ) ) {
return $block_content;
}
$dom = new Dom_Document_Helper( $block_content );
$list_element = $this->find_post_template_list( $dom );
// If we can't find the post-template list, leave the original content untouched so we never
// degrade output for markup shapes we don't recognize.
if ( null === $list_element ) {
return $block_content;
}
$items = $this->extract_list_items( $dom, $list_element );
if ( empty( $items ) ) {
return $block_content;
}
$columns = $this->get_column_count( $parsed_block, $dom, $list_element );
// Single-column (list/flow/constrained) layouts already stack correctly in email; only the
// multi-column grid/flex layouts need to be rebuilt as a table.
if ( $columns < 2 ) {
return $block_content;
}
// The layout width (minus the email's root padding) is what each cell's images are sized to,
// so an image CDN / Outlook get a concrete pixel width rather than the intrinsic file width.
$layout_width = (int) Styles_Helper::parse_value( $rendering_context->get_layout_width_without_padding() );
return $this->build_grid_table( $items, $columns, $dom, $list_element, $layout_width );
}
/**
* Locate the post-template list within the rendered content.
*
* The list is matched by its `wp-block-post-template` class rather than by being the first
* `
`, so a sibling list that happens to appear earlier in the markup can't be mistaken for
* the repeater. Returns null when no such list is present.
*
* @param Dom_Document_Helper $dom Parsed block content.
* @return \DOMElement|null
*/
private function find_post_template_list( Dom_Document_Helper $dom ): ?\DOMElement {
foreach ( $dom->find_elements( 'ul' ) as $list_element ) {
// Match `wp-block-post-template` as a whole class token, not a substring, so an unrelated
// list whose class merely contains the string (e.g. `my-wp-block-post-template-wrapper`)
// isn't mistaken for the repeater and rebuilt.
$classes = preg_split( '/\s+/', trim( $dom->get_attribute_value( $list_element, 'class' ) ) );
if ( is_array( $classes ) && in_array( 'wp-block-post-template', $classes, true ) ) {
return $list_element;
}
}
return null;
}
/**
* Extract the inner HTML of each direct-child `
` of the post-template list.
*
* Only direct children are collected, so a nested list inside a post's content (e.g. a
* `core/list` in an excerpt) contributes its markup to the item it lives in rather than being
* mistaken for additional repeater items.
*
* @param Dom_Document_Helper $dom Parsed block content.
* @param \DOMElement $list_element The post-template list element.
* @return array Inner HTML of each list item, in document order.
*/
private function extract_list_items( Dom_Document_Helper $dom, \DOMElement $list_element ): array {
$items = array();
foreach ( $list_element->childNodes as $node ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( $node instanceof \DOMElement && 'li' === $node->tagName ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$items[] = $dom->get_element_inner_html( $node );
}
}
return $items;
}
/**
* Determine how many columns the grid should render.
*
* Prefers the block's own `layout.columnCount` attribute and falls back to the `columns-N` class
* WordPress core stamps on the rendered list, so it still works when the parsed attributes are
* sparse. Non-grid/flex layouts always resolve to a single (stacked) column.
*
* @param array $parsed_block Parsed block data.
* @param Dom_Document_Helper $dom Parsed block content.
* @param \DOMElement $list_element The post-template list element.
* @return int Column count (at least 1).
*/
private function get_column_count( array $parsed_block, Dom_Document_Helper $dom, \DOMElement $list_element ): int {
$layout = $parsed_block['attrs']['layout'] ?? array();
$type = is_array( $layout ) && isset( $layout['type'] ) && is_string( $layout['type'] ) ? $layout['type'] : '';
// A layout that is neither grid nor flex (default, constrained, flow) stacks in one column.
if ( '' !== $type && 'grid' !== $type && 'flex' !== $type ) {
return 1;
}
$columns = 0;
if ( is_array( $layout ) && isset( $layout['columnCount'] ) && is_numeric( $layout['columnCount'] ) ) {
$columns = (int) $layout['columnCount'];
}
// Fallback: read the `columns-N` class WordPress core adds to the list wrapper.
if ( $columns < 1 && preg_match( '/(?:^|\s)columns-(\d+)(?:\s|$)/', $dom->get_attribute_value( $list_element, 'class' ), $matches ) ) {
$columns = (int) $matches[1];
}
if ( $columns < 1 ) {
return 1;
}
return min( self::MAX_COLUMNS, $columns );
}
/**
* Build the grid as one `
` per row wrapped in a container table.
*
* Follows the tiled-gallery pattern ({@see Gallery::build_gallery_table()}): items are chunked
* into rows of `$columns` and each row is its own fixed-layout table, so every cell keeps a
* consistent width regardless of how many items the final (possibly partial) row holds.
*
* @param array $items Inner HTML of each list item.
* @param int $columns Number of columns.
* @param Dom_Document_Helper $dom Parsed block content.
* @param \DOMElement $list_element The post-template list element (for wrapper classes).
* @param int $layout_width Available layout width in px.
* @return string Grid table HTML.
*/
private function build_grid_table( array $items, int $columns, Dom_Document_Helper $dom, \DOMElement $list_element, int $layout_width ): string {
$cell_width = $this->get_cell_width( $layout_width, $columns );
$rows = array();
$item_count = count( $items );
for ( $i = 0; $i < $item_count; $i += $columns ) {
$rows[] = $this->build_grid_row( array_slice( $items, $i, $columns ), $columns, $cell_width );
}
$grid_content = implode( '', $rows );
$original_class = $dom->get_attribute_value( $list_element, 'class' );
$table_attrs = array(
'class' => trim( 'email-block-post-template ' . Html_Processing_Helper::clean_css_classes( $original_class ) ),
'style' => 'width: 100%; border-collapse: collapse;',
'width' => '100%',
);
return Table_Wrapper_Helper::render_table_wrapper( $grid_content, $table_attrs );
}
/**
* Estimate the rendered pixel width of a single grid cell's content area.
*
* The layout width is split evenly across the columns and the per-cell padding is removed from
* both sides. Used to give each rebuilt image a concrete `width` attribute (the Outlook fallback)
* instead of the intrinsic file width, which Outlook would otherwise honor literally and blow the
* cell open.
*
* @param int $layout_width Available layout width in px.
* @param int $columns Number of columns (>= 2; a grid is only built for multi-column layouts).
* @return int Cell content width in px (at least 1).
*/
private function get_cell_width( int $layout_width, int $columns ): int {
$cell_width = (int) floor( $layout_width / $columns ) - ( 2 * self::CELL_PADDING );
return max( 1, $cell_width );
}
/**
* Build a single grid row as its own fixed-layout table.
*
* Every cell is a fixed `100 / $columns` percent wide and a partial final row is padded with
* empty cells, so items stay aligned to their column and keep a uniform width across rows (unlike
* the gallery, which stretches a partial row to fill the width). This matches how a CSS grid keeps
* column tracks consistent — important when the items are logos that shouldn't change size row to
* row.
*
* @param array $row_items Inner HTML of the items in this row.
* @param int $columns Total number of columns.
* @param int $cell_width Cell content width in px.
* @return string Row table HTML.
*/
private function build_grid_row( array $row_items, int $columns, int $cell_width ): string {
$cell_width_percent = 100 / $columns;
$cells = '';
for ( $col = 0; $col < $columns; $col++ ) {
$cell_content = isset( $row_items[ $col ] ) ? $this->prepare_item_content( $row_items[ $col ], $cell_width ) : '';
$cell_attrs = array(
'style' => sprintf(
'width: %s; padding: %dpx; vertical-align: top; text-align: center;',
Html_Processing_Helper::sanitize_css_value( sprintf( '%.4f%%', $cell_width_percent ) ),
self::CELL_PADDING
),
'valign' => 'top',
);
$cells .= Table_Wrapper_Helper::render_table_cell( $cell_content, $cell_attrs );
}
return sprintf(
'