Skip to content

Twig Integration

The Twig integration lets you build Astro Islands using Twig.js templates — the JavaScript implementation of the Twig templating language. A component is a native .twig file that you import directly into an Astro page. The island’s props are passed to the template as the render context, so {{ variables }} and Twig filters/tags are resolved on the client.

A Twig component is a native .twig file. The integration registers a Vite loader, so you can import a .twig file directly as an Astro Island component. Props passed on the island become the render context, so reference them with {{ }}:

{# src/framework/twig/MyComponent.twig #}
{% set count = initialCount|default(0) %}
<div class="my-component">
<pre class="count">{{ count }}</pre>
<button class="add">+</button>
<script>
(function () {
const container = (document.currentScript && document.currentScript.parentElement)
|| document.querySelector('.my-component');
let count = {{ count }};
const countEl = container.querySelector('.count');
container.querySelector('.add').addEventListener('click', function () {
count += 1;
countEl.textContent = count;
});
})();
</script>
</div>

The renderer reads the .twig file’s contents, compiles it with Twig.twig({ data }), and calls .render(props) on the client. Anything Twig.js understands — {{ value }}, {% set %}, {% if %}, {% for %}, comments ({# … #}), and filters like |default, |merge, or |upper — works against the props you pass on the island.

*** Note ***: Use Twig’s |default(...) filter for any value that may be missing so the rendered markup (and any inline script) stays valid when a prop is omitted. As with the Vanilla JS integration, be careful with global variables in the script tag so nothing leaks out of the island.

Twig’s asset() function — the same one the Symfony Twig bridge provides in PHP — is supported. A .twig file cannot run TypeScript imports, so the integration resolves each asset() call at build time and replaces it with the bundled asset URL. The referenced file is emitted and hashed by Vite just like an asset imported from a framework component:

<img alt="Logo" src="{{ asset('images/logo.png') }}" />

Paths resolve like this:

  • A plain path (images/logo.png) resolves from the project’s src directory, the way PHP’s asset() resolves from the public directory. A leading / is optional, so asset('/images/logo.png') is the same path.
  • A relative path (./logo.png, ../images/logo.png) resolves from the template that uses it, including when that template was pulled in by an {% include %}.
  • A namespaced path (@name/logo.png) resolves through the namespaces option, exactly as an include does.

Change the base directory used for plain paths with the assets option:

astro.config.mjs
import twig from "islands-integrations/twig";
export default defineConfig({
integrations: [
twig({
assets: "./src/images",
include: ["src/framework/twig/*"],
}),
],
});

The resolved URL is substituted as a Twig string, so it can be used anywhere an expression is allowed — in {{ }}, in {% set logo = asset('images/logo.png') %}, or with a filter applied.

Because the call is resolved at build time, the path has to be a static, quoted string. A dynamic path such as asset(logoVariable) fails the build, as does a path that points at a file that does not exist. Assets that are only known at runtime can still be resolved in the .astro page and passed in as props:

{% if logo %}<img alt="Logo" src="{{ logo }}" />{% endif %}

{% include %} works across files. Because islands render in the browser — where Twig.js has no filesystem loader — the integration resolves includes at build time and inlines the referenced template into the island. Paths resolve relative to the including file, and the inlined markup shares the island’s props as its render context:

{# src/framework/twig/Card.twig #}
{% include "./partials/header.twig" %}
<div class="card-body">{{ body }}</div>

Includes may be nested, and {% include "…" ignore missing %} is honored when the target file does not exist. An include that forms a cycle, or that points at a missing file without ignore missing, fails the build with an error.

Includes can also use Twig namespaces (@name/...) so templates reference a shared library by an alias instead of a long relative path. Map each namespace to a base directory with the namespaces option in astro.config.mjs:

astro.config.mjs
import twig from "islands-integrations/twig";
export default defineConfig({
integrations: [
twig({
include: ["src/framework/twig/*"],
namespaces: {
"@items": "./src/framework/twig/items",
},
}),
],
});

A namespaced include then resolves @items to its configured directory:

{% include "@items/components/element.twig" %}

Namespace keys may be written with or without the leading @ ("@items" and "items" are equivalent), and relative base directories resolve from the project root. An include that uses a namespace with no matching entry fails the build with an error.

The with { … } and only modifiers on an include are honored. Use with { … } to remap or supply variables for the included template, and add only to isolate it from the surrounding context so it sees just the variables you pass:

{% include "@items/components/element.twig" with {
content: content,
} %}

Some Twig features still rely on a runtime loader and are not supported, so keep those self-contained:

  • Dynamic include paths ({% include someVariable %}) — only static, quoted paths are inlined.
  • Macros ({% import %} / {% from %}) and template inheritance ({% extends %} / {% block %}).

Slots are not supported in the Twig integration. Pass content in as props and render it with {{ }} instead.

Nano Stores are not supported in the Twig integration. There is no binding library for Twig, and a .twig file cannot run imports — neither the template itself nor its inline <script>, which is re-created as a classic script when the island hydrates — so a store can never be created or read from within the component.

Pass the values a Twig island needs in as props instead. If a component has to share state with other islands or with OutSystems, build it with an integration that supports Nano Stores, such as the Vanilla JS integration or one of the framework integrations.

Register the integration’s Vite loader on the Twig project in vitest.config.ts so tests see the same template the island renders, with {% include %} tags inlined and asset() paths resolved:

vitest.config.ts
import { twigLoader } from "islands-integrations/twig";
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
projects: [
{
plugins: [twigLoader()],
test: {
environment: "happy-dom",
globals: true,
include: ["test/integration/twig/**/*.test.ts"],
name: "twig",
setupFiles: ["test/setup-test-env.ts"],
},
},
],
},
});

twigLoader() takes the same assets and namespaces options as the integration, and resolves them from the directory Vitest runs in. The scaffolded vitest.config.ts casts the plugin with as any, as it does for the other framework plugins, because Vitest and Vite can resolve to different copies of the plugin types.

Then use @testing-library/dom directly. Import the template with Vite’s ?raw suffix, render it with Twig.twig({ data }).render(props) before setting document.body.innerHTML, then execute the scripts using new Function so they run in the test’s global context:

import { fireEvent, screen } from "@testing-library/dom";
import Twig from "twig";
import template from "../../../src/framework/twig/MyComponent.twig?raw";
function renderComponent(props: Record<string, unknown> = {}) {
document.body.innerHTML = Twig.twig({ data: template }).render(props);
document.body.querySelectorAll("script").forEach((script) => {
new Function(script.textContent ?? "")();
});
}
test("increments counter", () => {
renderComponent({ initialCount: 5 });
fireEvent.click(screen.getByRole("button"));
expect(document.querySelector(".count")?.textContent).toBe("6");
});

new Function is required because innerHTML does not execute <script> tags, and replaceChild does not execute scripts in happy-dom.

Use Playwright as with any other framework. Navigate to the page and interact with elements normally:

import { expect, test } from "@playwright/test";
test.beforeEach(async ({ page }) => {
await page.goto("/twig/my-component");
});
test("increments counter", async ({ page }) => {
await page.getByRole("button", { name: "+" }).click();
await expect(page.locator("pre")).toContainText("6");
});