Skip to content

Repository files navigation

ALTO Twig Code Highlight

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.

About

Twig extension for alto/code-highlight: {% code_highlight %} tag and |code_highlight filter for server-side highlighting

Topics

Resources

Code of conduct

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Contributors

Languages