Skip to content

Instantly share code, notes, and snippets.

@allenmoore
Forked from jonathantneal/README.md
Last active April 16, 2019 22:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allenmoore/8bff2e95b35aea0bc549a2fcd3fccb07 to your computer and use it in GitHub Desktop.
Save allenmoore/8bff2e95b35aea0bc549a2fcd3fccb07 to your computer and use it in GitHub Desktop.
CSS Modules in PHP

CSS Modules lets you write and use simple class names rather than remembering and maintaining long unique class names for every component. CSS Modules mutates all of your classnames from each partials into new, completely unique classnames that will not conflict when they are bundled together into your main CSS file. Then, a JSON file is generated that maps the happy classnames from each file to the unique classname in the combined file. You load this map in PHP, and begin using the easy-to-remember classnames as you wish.

<?php $css_modules = new CSS_Module( get_template_directory() . '/assets/css/theme.json' ); ?>
<?php $article_cn = $css_modules->get_class_names( 'components/_main-article.css' ); ?>
<article class="<?php echo esc_attr( $article_cn( 'container' ) ); ?>">
<h1 class="<?php echo esc_attr( $article_cn( 'title' ) ); ?>">My style is scoped.</h1>
</article>
<article class="_container_1d980_1">
<h1 class="_container_23d3a_2">My style is scoped.</h1>
</article>
<?php
class CSS_Module {
private $json = array();
public function __construct( $map ) {
// Check if the file exists before calling it.
if ( file_exists( $map ) ) {
$this->json = json_decode( file_get_contents( $map ), true );
}
}
public function get_class_names( $path ) {
// Check if $path are set to prevent errors.
if ( ! isset( $path ) ) {
return;
}
// Pass the anonymous function as a callback to return.
$callback = function ( $key ) use ( $path ) {
return $this->get_class_name( $path, $key );
};
return $callback;
}
public function get_class_name( $path, $key ) {
// Check if $path and $key are set to prevent errors.
if ( ! isset( $path ) || ! isset( $key ) ) {
return;
}
$class_name = $this->json[ $path ][ $key ];
return $class_name;
}
}
{
"components/_main-article.css": {
"container":"_container_1d980_1",
"title":"_container_23d3a_2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment