Search code examples
javascripthtmlcsstemplate-engine

engine for editing CSS


I'm working on a web editor where user can customize some look & feel of the portal. To achieve this I was thinking under the hood the tool creates a CSS file.

For example, I'm giving user an UI editor where he can select font name and font size for page header, so the created CSS file should be like:

.header {
  font-size: fontSize;
  font-familiy: fontFamiliy;
}

where fontSize and fontFamily are values from editor.

The issue is I'm not sure what's the best way to do this. The user needs to be able to go back to the editor and edit values, so the engine needs to produce CSS but it also needs to store and load values.

Also, the font size and family is just a simple example, the customization features can be more complex.

One idea is to write code which creates the CSS text dynamically based on values in editor, something like:

var cssString = '.header {';
cssString = 'font-size: ' + fontSize + ';';

For loading, parse the CSS text and retrieve values, using regular expressions or something similar.

But I feel like this is not the best approach.


Solution

  • I suggest using LESS compiler together with LessPHP compiler

    [variables.less]
    @black: #000;
    @red: #f00;
    @green: #0F0;
    @blue: #00F;
    
    [editor]
    
    <label>
        Font color:
        <select name="Less[header][color]">
            <options value="@black">Red</options>
            <options value="@red">Red</options>
            <options value="@green">Red</options>
            <options value="@blue">Red</options>
        </select>
    </label>
    
    <label>
        Header background color color:
        <select name="Less[header][background-color]">
            <options value="@black">Red</options>
            <options value="@red">Red</options>
            <options value="@green">Red</options>
            <options value="@blue">Red</options>
        </select>
    </label>
    
    ...
    
    [makeLess.php]
    $less = '';
    
    foreach ($_POST['Less'] as $element) {
        $less .= ".{$element} {\r\n";
            foreach ($element as $attribute => $value) {
                $less .= "\t{$attribute}: {$value}\r\n";
            }
    
        $less .= "}\r\n";
    }
    
    $db->save($_POST['Less']); // Delete old values, insert new. No need to check if changed.
    file_put_contents(__DIR__.'/phpLess.less', $less);
    
    require "lessc.inc.php";
    
    $less = new lessc();
    echo $less->checkedCompile(__DIR__.'/phpLess.less', __DIR__'/style.css');
    

    Keep all Less variables as PHP array (hard-coded maybe?) so that you can reuse that and create Less variables file from PHP array.