Feature idea: #style helper

What does everyone think about adding a #style helper to express-hbs? The idea would be to add functionality similar to the now-deprecated scoped attribute for style tags e.g. a partial could look like:

<div>
<p></p>
</div>

{{#style}}
p {
   color: red;
}
{{/style}}

The benefit here is to make the main CSS more manageable by modularizing it in a fashion similar to Vue, CSS modules, or any of many other choices.

The script helper would prefix the selectors and add a corresponding script tag in the head. The helper could optionally take a block parameter to allow it to place the scripts into the head.

What does the team think? Would a PR be welcomed or met with opposition?

This is already possible with the contentFor and block helpers:

{{!-- layout --}}
<head>
  {{!-- ...}}
  {{{block "scopedStyles"}}}


{{!-- template --}}
{{#contentFor "scopedStyles}}
<style>
</style>
{{/contentFor}}

That works, but it creates a global style and the user has to ensure it doesn’t conflict with other styles in the theme (i.e. normal CSS).

What I’m proposing is the concept of a ‘scoped’ style where the helper guarantees that the styles only apply to the partial and nothing else in the DOM. In my original example, only the p tag in the declared div would be red and the rest of the paragraph tags in the DOM would be unchanged.

The mechanism to make this work is:

  • create a unique id for each partial
  • attach the id to the parent element of the partial
  • prefix all styles with something like data-attr[id]
  • finally add a style tag to the with the new styles (exactly as contentFor does)

This is how .vue files work with tags.

The real benefit here is the encapsulation of partials in a way that’s challenging in Ghost today.

1 Like