fat-free-framework

dynamically change CSS with fat free framework?


I am trying to use some shortcodes inside my CSS so I can change them all at once with fat free variables.

For example from my config.ini:

accentColor=8f0

And in my style.css would be:

.addToCart:hover {
    background-color: #[[accentColor]];
}

in my header.htm view file:

<link rel="stylesheet" href="{{@BASE}}/ui/css/style-user.php">

style-user.php:

<?php
    header("Content-type: text/css; charset: UTF-8");
    $fullpath='http://'.$_SERVER['SERVER_NAME'].'/ui/css/style.css';

    if(file_exists('style.css')){
        $search=array('[[accentColor]]','[[protectPhotoOpacity]]','[[protectPhotoPosition]]');
        $replace=array('{{ @accentColor }}','0.3', '30');
        echo str_replace($search,$replace,file_get_contents($fullpath));
    } else {
        echo "body {background-color: white;}";
    }
?>

It's finding style.css fine and the other shortcode changes are working. {{ @accentColor }} is not working in the style-user.php file but works fine in header.htm. What am I missing?

Is there a better way to go about doing this?

EDIT: I put the .php in the root folder instead of the /ui/css folder. Here's what I ended up with:

<?PHP
    $f3=require('lib/base.php');
    $f3->config('options.ini');
    $f3->set('CACHE',TRUE);
    echo Template::instance()->render('ui/css/style.css','text/css');
?>

And then inside the css file, just use the {{ @accentColor }} template variables like normal.


Solution

  • It's finding style.css fine and the other shortcode changes are working. {{ @accentColor }} is not working in the style-user.php file but works fine in header.htm. What am I missing?

    I assume that you are using F3's templating system to render header.htm. It looks like you are not using the template system to render the CSS file.

    I would propose to utilize the template system and template variables (like {{ @accentColor }}). Then you would be able to cache the parsed template files and/or the resulting CSS files for performance reasons.

    Your code could look similar to the following snippet:

    <?php
    
    // Setup F3 here.
    // You could utilize the routing system or skip routing and return only the CSS file.
    // I would prefer the routing system with a cached route.
    
    echo Template::instance()->render(
        'style.css', // Your CSS file stored in one of the `UI` directories
        'text/css',
        [
            'accentColor' => '#123456', // Specify variables or forward variables from a configuration file
        ]
    );
    

    Of course, there are other solutions. I would either register a CSS route or provide a PHP file that is bootstrapping F3 to render the CSS file with your variables.