Extensions and front matter | laravel-markdown-rust | Spatie       

 SPATIE  

laravel-markdown-rust
=====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-markdown-rust](https://spatie.be/docs/laravel-markdown-rust/v1)  Extensions and front matter

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-markdown-rust/v1) 

  Extensions and front matter    
- [ Introduction ](https://spatie.be/docs/laravel-markdown-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-markdown-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-markdown-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-markdown-rust/v1/usage)
- [ Extensions and front matter ](https://spatie.be/docs/laravel-markdown-rust/v1/extensions)
- [ Testing ](https://spatie.be/docs/laravel-markdown-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-markdown-rust/v1/changelog)
- [ Views and components ](https://spatie.be/docs/laravel-markdown-rust/v1/views)

 Extensions and front matter
===========================

###  On this page 

1. [ YAML front matter ](#content-yaml-front-matter)
2. [ Custom inline parsing and node rendering ](#content-custom-inline-parsing-and-node-rendering)

YAML front matter
-----------------------------------------------------------------------------------------------------------

Enable front matter explicitly and keep metadata separate from the HTML:

```
use spatie_markdown::MarkdownRenderer;

let result = MarkdownRenderer::new()
    .front_matter(true)
    .convert_to_html("---\ntitle: My title\ntags: [rust, markdown]\n---\n# My title")?;

assert_eq!(result.front_matter.unwrap()["title"].as_str(), Some("My title"));
assert_eq!(result.html, "<h1 id=\"my-title\">My title</h1>\n");
```

- `to_html` returns only the HTML and applies the same header removal.
- Headers must begin on the first line with `---` and end with `---` or `...`. LF and CRLF are supported.
- An unclosed header stays ordinary Markdown. Invalid YAML returns `Error::FrontMatter`.
- Metadata may contain nested mappings, sequences and typed scalar values. It never selects or executes an application layout automatically.

Custom inline parsing and node rendering
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

An `Extension` works on the parser's typed events. Use it to add parser options, recognize inline text, or replace block/inline nodes with generated HTML. The example replaces the thematic break renderer:

```
use spatie_markdown::{Error, Extension, MarkdownRenderer, Options, pulldown_cmark::Event};

#[derive(Debug)]
struct Divider;

impl Extension for Divider {
    fn cache_key(&self) -> String { "divider-v1".into() }

    fn options(&self) -> Options { Options::ENABLE_FOOTNOTES }

    fn transform(&self, events: Vec<Event<'static>>) -> Result<Vec<Event<'static>>, Error> {
        Ok(events.into_iter().map(|event| match event {
            Event::Rule => Event::Html("<pre class=\"divider\">==============================</pre>\n".into()),
            event => event,
        }).collect())
    }
}

let renderer = MarkdownRenderer::new().add_extension(42, Divider);
assert_eq!(renderer.to_html("---")?, "<pre class=\"divider\">==============================</pre>\n");
```

- Higher priorities run first. Equal priorities keep registration order.
- Extensions run before built-in heading/code rendering, so they can replace those blocks too.
- Preserve balanced start/end events. When replacing a full block, consume its whole event sequence.
- `Event::Text` contains decoded text. `Event::Code` contains inline code. Track `Tag::CodeBlock` boundaries to avoid interpreting custom syntax inside fenced or indented code.
- Native parser events can split adjacent text. An extension that recognizes multi-character syntax should combine the relevant text events before matching.
- Source HTML has already been escaped in safe mode. Extension-generated HTML is sanitized after rendering; `RawHtml::Allow` disables that sanitization too. Only install trusted Rust extensions.
- Return `Error::Extension(Box::new(error))` for an extension failure. The error must implement `std::error::Error + Send + Sync + 'static`. Its concrete type remains available through `Error::source` for downcasting. Failed rendering is not cached.
- Include extension version and all output settings in its cache identity. Change the identity whenever its output changes.

The application owns each renderer. Replace `MarkdownConfig::renderer`, register a customized renderer through the native service container, or clone one for a single component. There are no package models or jobs to subclass, and no queue or database side effects.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
