In this tutorial, we'll create a helper function in a Laravel application to convert Markdown content to HTML using the league/commonmark library. We'll cover the steps to create a helper file, include it in our Laravel project, and use it in a Blade template. This mechanism is used in Laravel 11 to make functions globally available.
The alternative is to handle the Markdown conversion in controller before passing the data to the view, so we no longer need to create a helper file:
use League\CommonMark\CommonMarkConverter; public function show($id) { $course = Course::find($id); $converter = new CommonMarkConverter(); $post->description = $converter->convertToHtml($post->description); return view('post.show', compact('post')); }
First, we install league/commonmark library via Composer:
composer require league/commonmark
Next, we'll create a helpers.php file to define our helper function. This file can be placed in the app directory or any other preferred location.
touch app/helpers.php
Open app/helpers.php and add the following content:
<?php use League\CommonMark\CommonMarkConverter; if (! function_exists('markdownToHtml')) { function markdownToHtml($markdown) { $converter = new CommonMarkConverter(); return $converter->convertToHtml($markdown); } }
To ensure Laravel automatically loads the helpers.php file, we need to modify the composer.json file to add the path to helpers.php under the autoload section:
"autoload": { "files": [ "app/helpers.php" ] }
After modifying composer.json, regenerate the Composer autoload files by running:
composer dump-autoload
With the helper function defined and loaded, we can now use it in the Blade templates to convert Markdown to HTML:
<div> {!! markdownToHtml($post->description) !!} </div>
This tutorial is provided to show how we can make custom functions available in blade templates.
The above is the detailed content of Using Helper Functions to Convert Markdown to HTML in Laravel 11. For more information, please follow other related articles on the PHP Chinese website!