How to create custom CSS "on the fly" based on account settings in a Django site? - css

So I'm writing a Django based website that allows users select a color scheme through an administration interface.
I already have middleware/context processors that links the current request (based on domain) to the account.
My question is how to dynamically serve the CSS with the account's custom color scheme.
I see two options:
Add a CSS block to the base template that overrides the styles w/variables passed in through a context processors.
Use a custom URL (e.g. "/static/dynamic/css/< website_id >/styles.css") that gets routed to a view that grabs all the necessary values and creates the css file.
I'm content with either option, but was wondering if anyone else out there has dealt with similar problems and could give some insight as to "Best Practices".
Update : I'm leaning towards option number 2, as I think this will allow for better caching down the road. So it's dynamic the first time, gets stored in memcache (or whatever), and invalidated when a user updates their settings in the admin site.
Update: Firstly, I'd like to thank everyone for their suggestions thus far. All the answers thus far have focused around generating static files. Though this would work great in production, it feels like a tremendous burden during development. If I wanted to add a new element to be styled, or tweak existing styles I'd have to go through and recreate each and every css file. Sure, this could be done with a management command, but I just don't feel it's worth it. Doing it dynamically would add 1 maybe 2 queries to each page load, which is something I'm not worried about at this stage. All I need to know is that at some point I will be able to cache it without rewriting the whole thing.

I've used option #2 with success. There are 2 decent ways of updating the generated static files that I know of:
Use a version querystring like /special_path.css?v=11452354234 where the v parameter is generated from a database field, key in memcached, or some other persistent file. Version gets updated by admin, or for development you would just make the generation not save if the parameter was something special like v=-1. You'll need a process to clean up the old generations after some time.
Don't use a version querystring, but have it look first for the generated file, if it can't find it, it generates it. You can create a cron job or WSGI app that looks for filesystem changes for development, and have a hook from your admin panel that deletes generations after an update. Here's an example of the monitoring, which you would have to convert to be specific to your generations and not to Django. http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Monitoring%5FFor%5FCode%5FChanges

Could generate the css and store it in a textfield in the same model as the user profile/settings. Could then have a view to recreate them if you change a style. Then do your option 1 above.

Nice question.
I would suggest to pre-generate css file after colors scheme is saved. This would have positive impact on caching and overall page loading time. You can store your css files in directory /media/css/custom/<id or stometing>/styles.css or /media/css/custom/<id or sth>.css and in template add <link rel="stylesheet" href="/media/css/custom/{{some_var_pointing _to_file_name}}" />
You can also do the trick with some random number or date in css file name that could be changed each time file is saved. Thanks to this browser will load the file immediately in case of changes.
UPDATE: example of using model to improve this example
To make managing of those file easy you can create simple model (one per user):
class UserCSS(models.Model):
bg_color = models.CharField(..)
...
...
Fields (like bg_color) can represent parts of your css file. You can ovveride save method to add logic that creates css file for user (by rendering some template).
In case your file format change you can make changes in your's model definition (with some default values for new fields), make little changes in template and run save method for each exisintg instance of class. This would renew your css files.
That should work nicely.

I would create an md5 key with the theme elements, store this key in the user profile and create a ccs file named after this md5 key : you gain static file access and automatic theme change detection.

Related

Angular: loading scss depending on user

I have a sets of users that I need to create themes for. Depending on the user's account association I want to load different themes. For example if John Doe logs in I need to load up greenteam.scss. However, if Doug Smith logs in he should see blueteam.scss.
Those files are basically color and font settings used by other elements. greenteam may have $header-bg: green; and blueteam would have $header-bg: blue;.
My initial thought is to have a structure like this: /src/scss/client/_client-xxx.scss that says the background colors, font colors, etc variables set in the application. So, after login the system is told the person logged in is part of "greenteam" and /src/scss/client/_client-greenteam.scss is loaded to compile the colors and other settings together. This way I can just drop the new client theme in the directory and boom, new theme!
The number of "teams" is going to grow exponentially. I have no idea how many I'll ever have at any given point. This is why the "just change the body class" is worrisome as that will get very big and hard to manage.
It's also possible I don't have a good grasp on how angular builds itself out on the web as a user calls the pages/styles. It appears, at a glance, when deployed on the server angular compiles the scss down to css in the header and not loaded "on the fly". If that's the case it seems I'd have to load all the possible client css options and just show what matches (the body class route).
The user won't have control over their theme directly or be able to change it, the theme will be customized manually by a developer.
I would have suggested to change the body class, but, if you really want to apply css at runtime, you could try to:
compile the scss to css
insert it in the dom at runtime depending on the user
Check this topic which tells how to add a style at runtime, you could get the text content of the stylesheet from a database:
https://stackoverflow.com/a/524717/10899694

Dynamically changing less variables in .net

problem : i have to allow users to have different colors for buttons , icons , text color as per their preference using spectrum.js
i have tried to solve this using dotless for that i created a file .less and added all values. now issue is that i have to get values from databased based on loggedInuser and have to dynamically change
#back-color: blue;
#font-color: red;
to different values and this has to be done run time not compile time. i know it will cost me some delay but i dont know how to solve it other wise.
i have been thinking of different solution rather to have a less file why not on saving time i create a css file save in database and when user gets logged in create a css file and inject in to header
<link href="~/Content/dynamic.css" rel="stylesheet" />
can some one help me or any suggestion regarding this??
any help will be appreciated
Option 1
Implement special handler for resource, that represent css customized by user.
This handler must:
Make lookup (by userId) to cache where already rendered less (i.e. css) is stored;
If cache has entry for requested user, then write css to response and finish handling of this request;
If cache has no entry for requested user, then render less for this user, store it in cache and go to step 2.
You also should remove/update cache entry when user changes his color theme.
You can implement cache as you wish: in memory, inside database or inside static files that named (for example) like %userId%.css.
Option 2
Instead of render less on server side (and consume server resources) you can render less on client dynamically.
Exmaple: http://jsbin.com/wiqosutexe/5/edit?html,js,output
Include lessjs http://lesscss.org/#download-options;
Provide less template to client script (get with ajax, include in script itself or somehow else);
Use user preferences to make substitutions to less template.
Render template and insert results (plain css) into dynamically created style tag.

How to make sure changes to a Wordpress plugin won't be lost on plugin update?

I'm pretty sure I've read somewhere that you can actually move the main plugin *.php file to somewhere else (I assume under your theme directory) to have it safe in case you made changes to it and your plugin updates. I tried Google but I can't find anything. Google page with good results will suffice.
I've just experienced a situation where my 2 plugins which had its layout changed and accommodated my needs and I want to make sure it doesn't happen again. Apart from having the main file in another location, is there a way to move along any CSS and JS files as well?
In Concrete5 CMS there is a nice way of doing this, by creating a new folder inside a block of an addon (may be regarded as a WP plugin), inside of which you can create copies of main file, any CSS and JS files and then you can simply edit them and choose that template for a page location you are using that block in.
I assume there is no such thing in Wordpress but how close can I get?
UPDATE: I found where I applied that advice on creating a new instance of the file then moving it to the theme directory.
The plugin in question was HL-Twitter. These are the plugin files:
admin.php
archive.php
functions.php
hl_twitter.php
hl_twitter_archive.php
hl_twitter_widget.php
import.php
widget.php
Now, this is the top contents (commented out) of the hl_twitter_widget.php:
Widget Theme for HL Twitter
To change this theme, copy hl_twitter_widget.php
to your current theme folder, do not edit this
file directly.
Available Properties:
$before_widget
$after_widget
$before_title
$after_title
$widget_title
$show_avatars
$show_powered_by
$num_tweets: how many tweets to show
$tweets: array of $tweet
$tweet: object representing a tweet
$tweet->twitter_tweet_id
$tweet->tweet
$tweet->lat
$tweet->lon
$tweet->created
$tweet->reply_tweet_id
$tweet->reply_screen_name
$tweet->source
$tweet->screen_name
$tweet->name
$tweet->avatar
$user: represents the Twitter user (ONLY SET IF SHOWING A SINGLE USERS TWEETS!)
$user->twitter_user_id
$user->screen_name
$user->name
$user->num_friends
$user->num_followers
$user->num_tweets
$user->registered
$user->url
$user->description
$user->location
$user->avatar
So I was wrong about copying the main file (in this case hl_twitter.php), but still - this enabled me to edit the file outside the plugin directory and the system somehow checks for its existence and picks it up if exists.
If this behavior something that is natively supported by Wordpress or it has been integrated in the plugin itself?
With themes, Wordpress has a concept of "child themes" which allows exactly that: to keep changes separate from main theme, in case it changes.
I haven't yet found a way to do this with plugins.
I'm using a few tactics myself:
I bump plugin version to a very high number like 99.9. This way Wordpress won't ever update the plugin.
Store my plugins in version control (i use git, but it doesnt matter), this allows you to update the plugin, run the 'diff' tool and see what changes happend. If you don't like you just revert like it would be a bad code you've written. But this approach requires a bit of skill.
Are you talking about running parts of a modified 3rd party plugin, and an updated version, at the same time?
That's not going to be possible. There is no magical method of "preserve my changes and transfer them into the new version automatically". The way to go here is doing a diff between the edited version and the update, and integrating the changes in the actual source files.
The bottom line is, if you manually edit a third party plugin, you're in for manual review (and possibly rework) once an update takes place. That's why it's usually not a good idea to extensively modify third party plugins.
Well in fact, yes! There is some kind of way.
You have to remove the to be modificated plugin's original actions/filters and then add your altereted actions/filters.
If the desired plugin is even coded in OOP you can just inherit the whole class and rewrite the wanted functions (oh sorry: "methods". we're talking about OOP ;) ). Instantiate your inherited class and rest as above.
Maybe there are better ways! I already search for a method so that the original class won't even get loaded but our altered one instead but I'm no John Carmack.

Drupal - customizing $scripts output

Basically the issue im having is I have a custom theme, and I need to use $scripts to call the analytics code at the top (the link tracking settings) however this also loads loads of other cr*p js files I dont need or want.
All I want is the analytics stuff the module places in $scripts.
So can I somehow either:
A) Load only the analytics code via $scripts (.info file?)
B) Create a new region in .info file (e.g. $analytics) and call that via the template. But then how do I get the analytics code to output to this new region instead of $scripts?
Any help would be most appreciated.
A.
I would be wary of not outputting $scripts. The files that are output are needed for your other modules to work properly. If you want to reduce the scripts which are output then turn off modules that you don't need.
I agree that disabling the $scripts variable (or cleaning it out) will have some "undesired results". I can think of about half a dozen modules that I use on every build that have required js files.
Maybe you should look into the Google Analytic Module which uses the $footer variable instead of the $scripts.
http://drupal.org/project/google_analytics
I also use this module on all my builds as it provides some very easy integration of Drupal into GA including downloads, user roles, etc. (out of the box)
p.s.
Remember Drupal has a pretty good Performance settings that allow for the cache as well as consolidation css/js.
My final builds have 1 line of markup that calls ALL of my css for that page and one line that does the same for my js. It's been shown that consolidating your asset files into one large file rather then many small ones is a huge performance saver, more so then the size of the end file itself.

User generated custom css

Hey, anyone have any idea what the best way to allow users to save custom css would be? Specifically, there are about 4 color values that I would like to allow a user to choose and these colors would be used to create a custom theme for the user. I'm thinking save values in the database and then using dom:loaded with prototype to set the custom style values but I'm wondering if theres a faster way? Like dynamically creating css files or something?
and then using dom:loaded with prototype
Awww, don't do that! That won't work when JavaScript is turned off.
Approach 1: Static stylesheet, dynamic values in document head
For the sake of not having to work with a dynamically created style sheet, have a separate, static CSS file with all the definitions that won't change.
<link rel="stylesheet" href="styles/static.css" type="text/css">
<!-- Or whatever you name it -->
All the definitions that will change, you could put into the head of the HTML document, fetching the user-changeable values from a database.
<style type="text/css">
.classname { font-size: (fontsize); } <-- Insert dynamic value here
.classname { color: (color); } <-- Insert dynamic value here
....
<style>
that way, the majority of the CSS stays in static, cacheable files, while the dynamic part won't cause another HTTP request.
Approach 2: Dynamic stylesheet
If you have a lot of dynamically changing values, put the entire style sheet into a script file and output it, replacing placeholders with the values from the database.
The downside to this is that to force the browser to reload the style sheet on changes, you'll have to work with a version approach stylesheet.css?version=400 which is pretty complex to do, but can sometimes be more desirable than littering the head section with CSS.
You decide which approach suits your situation better. I find myself choosing the first one most often.
I would save the 4 values in the database and then create a css file from those values. You would want to make sure and cache the created css file for each user so you don't have to dynamically create it each page view.
Creating a custom css file adds another request the browser has to make so you would need to make sure your setting up the headers correctly to cache it. If the user does change their settings you would need do something to ensure the browser immediately stops cashing the old css file and loads the new file. One way to do this is to change the url of the css file.
Example:
/usercustom.css?version=(last saved date hash)
Instead I would use your first approach and create a JSON array that you inject into the page and then you use your javascript framework to load and use the array to style the page.
You could also store the color values in the cookie from the server and use and or write to them on the client.
I think that best way is to save it to Db, because you don't want to allow user to mess with your website. At least if some pages are public.
And I personally think that answers like "do it without JavaScript" is nothing but old school BS... Did they tried to turn of JavaScript today? I don't think so... And by this paragraph I don't mean that you have to do it using JavaScript. Do it in a way that suits your needs 🤔
Wish you nice Day

Resources