Search by

n5s / timber-weblink-extension

n5s

Symfony WebLink for Timber: preload(), preconnect() and other Twig functions that send resource hints in a Link HTTP header.

Package info

github.com/nlemoine/timber-weblink-extension

pkg:composer/n5s/timber-weblink-extension

Fund package maintenance!

Open Collective

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 4

Open Issues: 1

1.0 2020-03-31 19:38 UTC

This package is auto-updated.

Last update: 2026-11-05 10:03:21 UTC


README

Latest Version Packagist Coverage

Brings the Symfony WebLink Twig functions to Timber.

Resources declared in your templates with preload(), preconnect() and the other functions are sent in a Link HTTP header, so the browser can start fetching them before it parses the HTML.

Requirements

  • PHP 8.2+
  • WordPress 6.9+
  • Timber 2.0+

Installation

composer require n5s/timber-weblink-extension

The extension adds itself to Timber's Twig environment on the timber/twig filter: there is nothing to set up. It also works when Composer's autoloader is loaded before WordPress, as in Bedrock.

Usage

<link rel="stylesheet" href="{{ preload(theme.link ~ '/css/app.css', {as: 'style'}) }}">

Sends:

Link: <https://example.com/wp-content/themes/my-theme/css/app.css>; rel="preload"; as="style"
Function Relation
preload(uri, attributes) preload
dns_prefetch(uri, attributes) dns-prefetch
preconnect(uri, attributes) preconnect
prefetch(uri, attributes) prefetch
prerender(uri, attributes) prerender
link(uri, rel, attributes) any relation

Each function returns the URI unchanged, so you can call it where the URI is printed. Attributes are optional: {as: 'font', type: 'font/woff2', crossorigin: true} adds as="font"; type="font/woff2"; crossorigin to the link.

When the header is sent

The links of every template rendered while WordPress builds the page are sent in one Link header, once the page output is complete. This relies on the template enhancement output buffer added in WordPress 6.9: WordPress holds the output of the theme template until it ends, then fires the wp_finalized_template_enhancement_output_buffer action, while headers can still be sent.

On older WordPress versions, no header is sent. The buffer only covers front-end templates loaded by WordPress, not admin pages, REST or Ajax requests, and it is not started if your site turns it off with the wp_should_output_buffer_template_for_enhancement filter.

To send the header at another time, remove the action and call the function yourself:

remove_action('wp_finalized_template_enhancement_output_buffer', 'n5s\TimberWebLink\send_headers');

\n5s\TimberWebLink\send_headers();

Upgrading

From 1.x, see UPGRADE-2.0.

Contributing

See CONTRIBUTING.