alto / twig-code-highlight
Twig extension for Alto Code Highlight with code_highlight tag and filter
Fund package maintenance!
Requires
- php: ^8.4
- alto/code-highlight: *@dev
- twig/twig: ^3.23
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.94
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.5
This package is auto-updated.
Last update: 2026-04-17 01:15:57 UTC
README
Twig extension for alto/code-highlight that adds a block tag and a filter for rendering syntax-highlighted code in templates.
{% code_highlight %}
#[AsTwigExtension]
public function getFilters(): array
{
return array_all(
);
}
{% endcode_highlight %}
Requirements
- PHP
^8.4(>= 8.4.0, < 9.0.0) - Twig
^3.23(>= 3.23.0, < 4.0.0)
Installation
composer require alto/twig-code-highlight
Register extension
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 => fn () => new CodeHighlightRuntime( $extension->getHighlighter(), $extension->getDefaultOptions(), ), ]));
Tag {% code_highlight %}
This tag highlights the enclosed code block and renders highlighted HTML output.
Example
{% code_highlight 'php' %}
<?php
echo "Hello world";
{% endcode_highlight %}
Options (arguments)
| Option | Type | Default | Behavior |
|---|---|---|---|
line_numbers |
bool | false |
Enables line numbers in output |
highlight_lines |
array | [] |
Only positive integers are used; other values are ignored |
Theme:
theme is not passable as a tag argument; configure the Highlighter theme when registering the extension.
See theme docs in the core library: https://github.com/phpalto/code-highlight.
Filter |code_highlight
This filter highlights a code string and returns highlighted HTML output.
Syntax:
{{ code|code_highlight(language, options) }}
Example
{{ snippet|code_highlight('javascript') }}
Options (arguments)
| Option | Type | Default | Behavior |
|---|---|---|---|
line_numbers |
bool | false |
Enables line numbers in output |
highlight_lines |
array | [] |
Only positive integers are used; other values are ignored |
Theme:
theme is not passable as a filter argument; configure the Highlighter theme when registering the extension.
See theme docs in the core library: https://github.com/phpalto/code-highlight.
Contributing
Contributions are welcome! Please feel free to submit issues or pull requests.
License
Released by the Alto project under the MIT License.