alto/twig-code-highlight

Highlight source code in Twig templates with a tag or filter.

Maintainers

Package info

github.com/altophp/twig-code-highlight

Homepage

Documentation

pkg:composer/alto/twig-code-highlight

Transparency log

Fund package maintenance!

smnandre

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-08-10 01:35 UTC

This package is auto-updated.

Last update: 2026-08-13 03:59:07 UTC


README

Highlight source code directly from Twig templates with a tag or filter powered by ALTO Code Highlight.

  PHP Version   CI   Packagist   License   GitHub Sponsors

Use the block tag for literal template content or the filter for dynamic source:

{% code_highlight 'php' %}
<?php echo 'Hello, Alto!';
{% endcode_highlight %}

{{ source|code_highlight('javascript') }}

Installation

Install ALTO Twig Code Highlight with Composer:

composer require alto/twig-code-highlight

The package requires PHP 8.4 or later, ALTO Code Highlight 1.x, and Twig 3.28 or later.

Setup

Register the extension and its runtime:

use Alto\Twig\CodeHighlight\CodeHighlightExtension;
use Alto\Twig\CodeHighlight\Runtime\CodeHighlightRuntime;
use Twig\RuntimeLoader\FactoryRuntimeLoader;

$extension = new CodeHighlightExtension();
$twig->addExtension($extension);

$twig->addRuntimeLoader(new FactoryRuntimeLoader([
    CodeHighlightRuntime::class => static fn (): CodeHighlightRuntime => new CodeHighlightRuntime(
        $extension->getHighlighter(),
        $extension->getDefaultOptions(),
    ),
]));

Default options may be configured on the extension:

$extension = new CodeHighlightExtension(defaultOptions: [
    'line_numbers' => true,
]);

Quick Start

{% code_highlight 'php' with {line_numbers: true, highlight_lines: [2]} %}
<?php

echo 'Hello world';
{% endcode_highlight %}

The language may be a Twig expression:

{% code_highlight language %}
const answer = 42;
{% endcode_highlight %}

Filter

{{ source|code_highlight('javascript') }}

Options are passed as the second argument:

{{ source|code_highlight('php', {line_numbers: true, highlight_lines: [1, 3]}) }}

Options

Option Type Default
line_numbers bool false
highlight_lines array<int> []

A language is required for both the tag and filter. Configure themes through the core Highlighter; see the theme guide.

Contributing

Contributions of all kinds are welcome. Visit the project on GitHub to report a bug, suggest a feature, or open a pull request.

Before submitting code, run:

# Runs PHP CS Fixer, PHPStan, and PHPUnit
composer qa

Changes to public behavior should include tests and documentation.

Support

ALTO Twig Code Highlight is open source. You can support its continued development through GitHub Sponsors.

Sharing this package with others or starring it on GitHub is also much appreciated.

License

ALTO Twig Code Highlight is released by ALTO PHP under the MIT License.