Adding a Class to a Partial

I know you can pass data to a partial but I’m a little confused how to access it. I want to be able to add a class based on where my partial will be used, so for example, it would look something like this if I was using it on a single post template:

@include('', ['class' => 'services-single'])

and if I wanted to include the partial on the home page, I could do:

@include('', ['class' => 'home'])

And then in the Services partial template, I want add that class in the first line to look like this:

<section class="INSERT THAT CLASS HERE">...</section>

I tried reading the Laravel Blade docs but I’ve been coming up short. Any ideas?

All @include('', ['class' => 'services-single']) does is make a variable available to that partial. If you want that in your class, you would need to echo the variable in your partial, i.e.:

<!-- partials/services -->
<section class="{{ $class }}">
1 Like

Perfect, that makes sense, I just couldn’t figure out the syntax. Thank you!

1 Like

If you want to make things a bit more exciting, you could look into components, which allow you to do fun stuff like

<!-- component file -->
<div {{ $attributes->merge([ 'class' => 'service' ]) }}>
  {{ $slot }}

<!-- usage in template -->
<x-service class="home">
  This is home.

<!-- renders as -->
<div class="service home">
  This is home.
1 Like

Interesting, I think that is more what of what I am looking for. I will definitely give that a go, thank you again!

This topic was automatically closed after 42 days. New replies are no longer allowed.