SPresnac's avatar

Laravel package to edit markdown files easy?

I do have markdown files in my project and they are rendered perfect, it's a statamic site ;)

My question is now if there is a laravel package to edit the generated markdown easily?! So, I do have to create or modify the existing files and have to update only some fields in the markdown attributes (the area on top) and I am wondering for some laravel package to to this "the laravel way".

Anybody has experience with that and can point me out to a fitting package?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

One possible solution is to use the Spatie/YamlFrontMatter package, which allows you to easily parse and modify the YAML front matter of a Markdown file. Here's an example of how you could use it in a Laravel controller:

use Spatie\YamlFrontMatter\YamlFrontMatter;

class MarkdownController extends Controller
{
    public function edit($filename)
    {
        $path = storage_path("app/markdown/{$filename}.md");
        $markdown = file_get_contents($path);
        $document = YamlFrontMatter::parse($markdown);

        // Access the YAML front matter as an associative array
        $attributes = $document->matter();

        // Modify the attributes as needed
        $attributes['title'] = 'New Title';

        // Convert the attributes back to YAML
        $yaml = Yaml::dump($attributes);

        // Replace the YAML front matter in the Markdown file
        $newMarkdown = "---\n{$yaml}---\n{$document->body()}";
        file_put_contents($path, $newMarkdown);

        return view('markdown.edit', compact('document'));
    }
}

In this example, we're assuming that the Markdown files are stored in the storage/app/markdown directory. We're also assuming that each file has a YAML front matter section at the top, which contains some attributes that we want to modify.

The YamlFrontMatter::parse method is used to parse the Markdown file and extract the YAML front matter and the body of the file. We can then access the YAML front matter as an associative array using the matter method.

We can modify the attributes as needed, and then convert them back to YAML using the Yaml::dump method. We then replace the original YAML front matter in the Markdown file with the new YAML, and save the modified Markdown file using the file_put_contents function.

Finally, we return a view that displays the modified Markdown file, so that the user can see the changes that were made.

Note that this is just one possible solution, and there may be other packages or approaches that are better suited to your specific use case.

Please or to participate in this conversation.