Roots Discourse

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('partials.services', ['class' => 'services-single'])

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

@include('partials.services', ['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('partials.services', ['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 }}
</div>

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

<!-- renders as -->
<div class="service home">
  This is home.
</div>
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!