laravel-code-sample maintained by ismailnakkar
laravel-code-sample
Highlights a code sample you write in a Blade slot, on the server with
tempest/highlight: no script draws it, and the text inside your <code> is
exactly the code, so a copy button pointed at it copies the code. Your app keeps its own component and markup; the
package hands it the highlighted HTML and the line count.
Install
Needs PHP 8.4+. It reads a Blade slot, so it is for Laravel views, but it calls no Laravel API.
composer require ismailnakkar/laravel-code-sample
There is nothing to publish or register. Style tempest's classes (hl-keyword, hl-variable, hl-value, …) in your
CSS.
Usage
Write a component that hands its slot to CodeSample::fromSlot() and draws the result in your own view:
use CodeSample\CodeSample;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
final class Code extends Component
{
public function __construct(public string $language, public ?string $id = null, private array $placeholders = []) {}
public function render(): \Closure
{
return fn (array $data): View => view('components.code', [
'sample' => CodeSample::fromSlot((string)$data['slot'], $this->language, $this->placeholders),
]);
}
}
{{-- resources/views/components/code.blade.php --}}
<pre dir="ltr"><code id="{{ $id }}">{!! $sample->html !!}</code></pre>
Then write the code in any view, indented with the markup around it, echoing values as usual:
<x-code language="json" id="api-reply">
{
"url": "{{ $shortUrl }}"
}
</x-code>
fromSlot(string $slot, string $language, array $placeholders = [])returns aCodeSamplewithhtml, the code highlighted and escaped, andlines, its line count, for a line-number gutter.- The slot. Its
{{ }}echoes arrive escaped and are decoded back to the code's own characters; the view's indentation is removed (Blade trims the first line, so the margin is the one the other lines share);\r\nreads as\n, and trailing space goes. $languageis a tempest/highlight language name:php,json,html,javascript,bash,sql, ….- Escaping. Everything in
htmlcomes escaped from the highlighter, so{!! !!}prints only markup it wrote. The characters tempest reads as its own markup (❶–❹,❿,{,}) are kept as code, never as its annotations. $placeholdersmaps a word in the code to an attribute name: after highlighting, each word becomes an empty<span data-…></span>a script can fill (a token shown only after a click, say). The word leaves the copied text.
API in brief
CodeSample::fromSlot($slot, $language, $placeholders = []) |
The slot's code, highlighted |
$sample->html |
The highlighted code, escaped, to print with {!! !!} inside your <code> |
$sample->lines |
The code's line count |
Testing your app
Nothing to fake: render your component with Blade::render() and read the <code>'s textContent.
Upgrading
The first release, 0.1.0, has nothing to upgrade from.
Licence
MIT.