aymericcucherousset / d2-symfony
Render D2 diagrams (d2lang.com) in Symfony & Twig: local binary or Kroki, cached, profiler-ready.
Package info
github.com/aymericcucherousset/d2-symfony
Type:symfony-bundle
pkg:composer/aymericcucherousset/d2-symfony
Requires
- php: >=8.2
- ext-phar: *
- ext-zlib: *
- psr/cache: ^2.0 || ^3.0
- symfony/config: ^6.4 || ^7.4 || ^8.0
- symfony/console: ^6.4 || ^7.4 || ^8.0
- symfony/dependency-injection: ^6.4 || ^7.4 || ^8.0
- symfony/http-client: ^6.4 || ^7.4 || ^8.0
- symfony/http-kernel: ^6.4 || ^7.4 || ^8.0
- symfony/process: ^6.4 || ^7.4 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- nyholm/symfony-bundle-test: ^3.1
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-symfony: ^2.0
- phpunit/phpunit: ^11.5
- symfony/cache: ^6.4 || ^7.4 || ^8.0
- symfony/filesystem: ^6.4 || ^7.4 || ^8.0
- symfony/framework-bundle: ^6.4 || ^7.4 || ^8.0
- symfony/twig-bundle: ^6.4 || ^7.4 || ^8.0
- twig/twig: ^3.21
Suggests
- symfony/twig-bundle: To render diagrams in templates with the |d2 filter
Provides
None
Conflicts
- twig/twig: <3.21
Replaces
None
This package is auto-updated.
Last update: 2026-11-27 20:08:30 UTC
README
Write D2 diagrams as text in your Twig templates and get inline SVG, rendered by Symfony.
Note
Early development (0.3): the API may change between minor versions. See the roadmap.
This diagram was rendered by the bundle itself from docs/example.d2.
Requirements
- PHP 8.2 or later
- Symfony 6.4, 7.4 or 8.x
- Twig 3.21 or later (
symfony/twig-bundle), for the|d2filter and{% d2 %}tag - The
d2binary, downloaded for you bybin/console d2:download(Linux, macOS and Windows on amd64 or arm64)
Installation
-
Install the bundle:
composer require aymericcucherousset/d2-symfony
With Symfony Flex, the bundle is registered automatically in
config/bundles.php. -
Download the
d2binary:bin/console d2:download
The command downloads d2 for your platform from the terrastruct/d2 releases, verifies its SHA-256 checksum and installs it in
var/d2/<version>/. Run it again with--forceto reinstall. Add/var/d2/to your.gitignore, and run the command in your deployment (or Docker build) too.The version is pinned (
d2.binary_version, a version tested with the bundle). Prefer your own installation? Install d2 in yourPATHor setd2.binary_path: the bundle uses, in order,d2.binary_path, the downloaded binary, thend2from thePATH.
Without Symfony Flex
Register the bundle in config/bundles.php:
return [ // ... Aymericcucherousset\D2Symfony\D2SymfonyBundle::class => ['all' => true], ];
Configuration
No configuration is required. Here is the full reference with the default values, to put in config/packages/d2.yaml if you need to change something:
d2: # How diagrams are rendered: binary, kroki or chain (see "Choosing a renderer"). renderer: binary # Renderers tried in order when renderer is "chain". chain: [binary, kroki] kroki: # Kroki server: the public instance or a self-hosted one. base_url: https://kroki.io # HTTP client service, e.g. a scoped client; a default client is used when it does not exist. http_client: http_client # Name of the d2 executable looked up in the PATH, or path to it. # ~ uses the binary installed by d2:download, then "d2" from the PATH. binary_path: ~ # Version installed by bin/console d2:download. binary_version: v0.9.0 # Where bin/console d2:download installs the binary. install_dir: '%kernel.project_dir%/var/d2' # Maximum rendering time in seconds, for the binary and Kroki; ~ disables the limit # (Kroki then uses the HTTP client defaults). timeout: 60 # Options applied to every diagram unless overridden. # ~ means "use the d2 default". defaults: theme: ~ # d2 theme ID, e.g. 200 (dark mauve) layout: ~ # layout engine: dagre (d2 default) or elk pad: ~ # padding around the diagram, in pixels (d2 default: 100) sketch: false # hand-drawn look # Cache rendered SVG (set to false to disable). cache: enabled: true pool: cache.d2 # PSR-6 pool service, created automatically twig: # Render static {% d2 %} tags when templates are compiled; ~ = when kernel.debug is false. prerender_static: ~
Invalid values (negative padding, unknown layout format, unknown keys…) are rejected when the container is built.
Usage
Twig
Pipe D2 source into the |d2 filter; it outputs the SVG markup, ready to inline in your HTML:
{{ 'shop -> payment: checkout'|d2 }}
Multi-line diagrams read best with a {% set %} block, and options override the configured defaults:
{% set architecture %}
direction: right
user -> app: HTTPS
app -> db: SQL
db: { shape: cylinder }
{% endset %}
<figure>
{{ architecture|d2({ theme: 200, sketch: true }) }}
</figure>
Available options: theme (int), layout (string), pad (int) and sketch (bool); null resets an option to the d2 default. Twig variables work as usual: {{ diagram.source|d2 }}.
The {% d2 %} tag lets you write the diagram directly in the template, with the same options:
{% d2 with { layout: 'elk' } %}
user -> app: {{ protocol }}
{% for service in services %}
app -> {{ service }}
{% endfor %}
{% endd2 %}
Twig variables and tags work inside the body; their output is not HTML-escaped, since it is D2 source (d2 escapes labels in the generated SVG).
PHP
Autowire the Renderer service anywhere in your application:
use Aymericcucherousset\D2Symfony\Core\Diagram; use Aymericcucherousset\D2Symfony\Core\Renderer; use Aymericcucherousset\D2Symfony\Core\RenderOptions; use Symfony\Component\HttpFoundation\Response; final class DiagramController { public function __construct(private Renderer $renderer) { } public function __invoke(): Response { $svg = $this->renderer->render(new Diagram( 'a -> b', new RenderOptions(layout: 'elk', sketch: true), )); return new Response($svg, headers: ['Content-Type' => 'image/svg+xml']); } }
Choosing a renderer
renderer |
Renders with | Use it when |
|---|---|---|
binary (default) |
the local d2 binary |
you can run binaries: fastest, works offline, no data leaves the server |
kroki |
a Kroki server over HTTP | the hosting platform forbids running binaries (some PaaS, serverless, shared hosting) |
chain |
each renderer of chain, in order |
you want a fallback, e.g. the binary in production and Kroki on machines where d2 is not installed |
# config/packages/d2.yaml d2: renderer: chain chain: [binary, kroki] # default order kroki: base_url: https://kroki.example.com # optional, defaults to https://kroki.io
In chain mode, the next renderer is only tried when the current one is unavailable: the d2 binary is missing or not executable, or the Kroki server cannot be reached or returns a server error (HTTP 5xx). D2 syntax errors and timeouts are thrown right away, since another renderer would not do better. When every renderer is unavailable, a NoRendererAvailableException lists each error.
Kroki receives the theme, layout, pad and sketch options. Options it does not support are ignored, and a warning is logged on the d2 channel. To authenticate against a self-hosted instance, point d2.kroki.http_client to a scoped client with the right headers.
Note
With kroki or chain, the diagram source may be sent to the Kroki server. Use a self-hosted instance for private diagrams.
Outside the bundle, the core classes can be used directly:
use Aymericcucherousset\D2Symfony\Core\BinaryRenderer; use Aymericcucherousset\D2Symfony\Core\ChainRenderer; use Aymericcucherousset\D2Symfony\Core\KrokiRenderer; use Symfony\Component\HttpClient\HttpClient; $renderer = new ChainRenderer([ new BinaryRenderer(), new KrokiRenderer(HttpClient::create(), 'https://kroki.io', timeout: 10.0, logger: $logger), ]);
Caching
Rendered SVG is cached in the cache.d2 pool (backed by cache.app), so each diagram is rendered by d2 only once. The cache key covers the D2 source, the options and the d2 version: diagrams are rendered again after a d2 upgrade (the version is checked every 5 minutes). To use another backend, point d2.cache.pool to any PSR-6 pool, or configure cache.d2 under framework.cache.pools.
Clear it with:
bin/console cache:pool:clear cache.d2
Pre-rendering static diagrams
When kernel.debug is false (production), {% d2 %} tags whose body and options are constant are rendered once, when the template is compiled, and the SVG is embedded in the compiled template. Since bin/console cache:warmup compiles every template, static diagrams then never call d2 at runtime, even with an empty cache.
A diagram is static when its body contains no Twig expression or tag and its options are a literal hash ({% d2 with { theme: 200 } %}). Diagrams that cannot be rendered at compile time (syntax error, d2 missing on the build machine…) are rendered at runtime as usual.
Pre-rendering is disabled in debug mode, as compiled templates outlive changes to the d2 configuration there. Force it either way with:
d2: twig: prerender_static: true # or false; ~ (default) = enabled when kernel.debug is false
Errors
Every exception thrown by the bundle implements Aymericcucherousset\D2Symfony\Core\Exception\D2Exception:
| Exception | Thrown when |
|---|---|
RenderException |
d2 rejects the source or rendering fails (timeout, Kroki HTTP error…); getD2Line() / getD2Column() locate the first D2 error, getD2Errors() lists them all, getD2Error() returns the raw d2 output |
BinaryNotFoundException |
the d2 binary is missing or not executable (run bin/console d2:download) |
RemoteUnavailableException |
the Kroki server cannot be reached or returns a server error (HTTP 5xx) |
NoRendererAvailableException |
in chain mode, every renderer is unavailable; getFailures() returns each error |
InvalidArgumentException |
a diagram or an option is invalid (empty source, unknown option…) |
BinaryNotFoundException, RemoteUnavailableException and NoRendererAvailableException implement RendererUnavailableException: catch it to handle "no renderer could run" separately from D2 errors.
In templates, Twig wraps them in a Twig\Error\RuntimeError pointing to the template line. For the {% d2 %} tag, a D2 syntax error points to the template line of the faulty D2 line, so the Symfony error page highlights it:
D2 syntax error at line 2, column 4: maps must be terminated with } in "page.html.twig" at line 14
(The mapping is exact for static bodies; Twig expressions printing several lines shift the lines after them.)
Roadmap
| Milestone | Goal |
|---|---|
| v0.1.0 — Working core | Render a D2 diagram to SVG from Twig using a manually installed binary. |
| v0.2.0 — Caching & Twig ergonomics | Cached rendering, {% d2 %} tag, readable errors. |
| v0.3.0 — Frictionless installation | The d2 binary is downloaded automatically. |
| v0.4.0 — Kroki renderer | HTTP renderer for environments where binaries cannot run. |
| v0.5.0 — Developer experience | Profiler panel, rendering CLI, fully typed options. |
| v0.6.0 — Formats & integrations | PNG/PDF output, .d2 files, Markdown code blocks. |
| v1.0.0 — Stabilization | Frozen API, complete documentation, release. |
Development
composer install composer ci # PHP-CS-Fixer + PHPStan + PHPUnit composer cs-fix # apply coding standards
Integration tests need the d2 binary on your PATH; they are skipped otherwise (set D2_REQUIRED=1 to make them fail instead).
To regenerate the README diagram after editing docs/example.d2:
d2 --pad=20 docs/example.d2 docs/images/example.svg
License
MIT — see LICENSE.