Highlight source code directly from Twig templates with a tag or filter powered by ALTO Code Highlight.
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') }}Install ALTO Twig Code Highlight with Composer:
composer require alto/twig-code-highlightThe package requires PHP 8.4 or later, ALTO Code Highlight 1.x, and Twig 3.28 or later.
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,
]);{% 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 %}{{ source|code_highlight('javascript') }}Options are passed as the second argument:
{{ source|code_highlight('php', {line_numbers: true, highlight_lines: [1, 3]}) }}| 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.
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 qaChanges to public behavior should include tests and documentation.
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.
ALTO Twig Code Highlight is released by ALTO PHP under the MIT License.