Skip to content

Instantly share code, notes, and snippets.

@snnsnn
Forked from jonathantneal/README.md
Created March 29, 2019 02:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save snnsnn/bbfd39359a8668c03ab0b304f36916c7 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 {
// CSS Modules by ID
private $collection = array();
// Create a new CSS Modules collection
public function __construct( $json_file ) {
if ( ! isset( $json_file ) || ! file_exists( $json_file ) ) {
return false;
}
// push the JSON data into this instance
$this->collection = json_decode( file_get_contents( $json_file ), true );
}
// Returns a function for returning class names of the specified CSS Modules ID
public function get_class_names( $id ) {
if ( ! isset( $id ) ) {
return false;
}
// return an anonymous function as a callback to return
$callback = function ( $class_name ) use ( $id ) {
return $this->get_class_name( $id, $class_name );
};
return $callback;
}
public function get_class_name( $id, $class_name ) {
if ( ! isset( $id ) || ! isset( $key ) || ! array_key_exists( $this->collection, $id ) ) {
return false;
}
$alt_class_name = $this->collection[ $id ][ $key ];
return $alt_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