[Blade] Inline styles

What is the best practice to add inline styles to a page in blade (sage9)?
The colors were selected by ACF input, hence I want to add these inline styles only for a particular page (blade template).
The (soberwp/)controller is meant to be only used for retrieving data, not for e.g. enqueueing styles.

It’s still data stored in the database, not sure why you wouldn’t consider that data.

Also, you say specifically “inline styles”, that is not enqueueing anything.

1 Like

Yes, inline styles like inserting a <style> element with inline styles into header/before body.
Either a blade @slot can be used or the native WordPress enqueue functionality - but how to properly call it from within blade template?

Here are some possible solutions if you want to add the styles from within the template.

Add a stack to head.blade.php inside the <head>

@stack('wp_head')

And in your template create a unique id to be able to limit the scope of the styles to this component.

$uniqid = uniqid('scope-');

Add the id to your component

<div id="{{ $uniqid }}">

Then write your styles and push them to the wp_head stack.

@push('wp_head')
<style>
#{{ $uniqid }} .element {
   color: {{ $color }};
}
</style>
@endpush

Alternatively, if you do not want to use a stack, add the styles as scoped styles just inside the component. (Only supported in Firefox but should work everywhere if you still include the uniqid).

<div id="{{ $uniqid }}">    
  <style scoped>
  #{{ $uniqid }} .element {
    color: {{ $color }};
  }
  </style>
  ...

Or add them to <head> with a action hook

@php
add_action('wp_head', function() use ($uniqid, $color) {
@endphp
  <style>
  #{{ $uniqid }} .element {
    color: {{ $color }};
  }
  </style>
@php
});
@endphp
2 Likes

The difficulty with a @stack is that all of the templates that are going to populate the stack must be called before the stack renders. If you’re rendering your @stack('wp_head') in app.blade.php, and pushing to it in page.blade.php I don’t think it’ll work, since the @stack call comes before anything has been pushed to it.

1 Like

Yes it will probably not be viable for every scenario. In your specific example however with a stack in app.blade.php (or any file added there with a @include) and push in page.blade.php (or any template deeper in the hierarchy) blade does some black magic and it will work just fine. I’m not able to find templates where it is not working at least. page.blade.php is our landing template here and not app.blade.php. @extends(‘layouts.app’) actually seems to be among the last things to be rendered even if it is at the top of the page.blade.php file (this was the reason behind sages incompatibility with a lot of plugins up until recently).

2 Likes