logo
podcast Podcast
get help Get Unstuck

When might you render a Blade template inline?

This isn't a feature I reach for frequently, but it's good to know it exists. Here is one use case where we found it quite handy.

Joel Clermont
Joel Clermont
2023-09-06

Each tip in this newsletter also exists as a Markdown file within the masteringlaravel.io tip archive. But if we include an internal link, I want to be able to use named routes with Laravel's route() helper. And if we include an image, I want it to take advantage of the Vite::asset() helper. How can we have a Markdown file that also supports Blade syntax?

The solution we chose is Laravel's inline Blade rendering.

In our case, we're using the excellent Orbit package, which allows us to treat Markdown files on disk as Eloquent models. It exposes the Markdown body as a content attribute, and we can use an Eloquent attribute to make sure it also gets passed through the Blade renderer. With essentially one line of code, we get Markdown content which also supports Blade syntax:

/**
 * Using blade render helper so that we can use routes and Vite assets in our markdown content.
 */
public function content(): Attribute
{
    return new Attribute(fn (string $content) => Blade::render($content));
}

This is very powerful! Notice too that we added a comment as to why we are doing this. This is not a typical feature for us, so having this reminder will help us remember the context in the future.

Here to help,

Joel

P.S. Ever wonder if your Laravel app could be more secure? Download our free book for 7 steps to review.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.