How to dynamically modify CSS using Python?
Question: I'm creating a Flask-based web app. I need to modify the CSS of an element
dynamically.

To be more specific, I have a file that I want to read from Python. Based on
what I read from the file, I want to modify the CSS of an element. Just to
give you an idea,

    
    
    with open('xyz') as f:
       if f.readline() == 'foo':
           $("#baz").css("visibility", "none")
    

I've tried using Opal with Ruby, however I'm unable to setup the 'opal-jquery'
stuff. Any guidance down either paths is appreciated.


Answer: If you are configuring the CSS as part of the backend rendering process, then
treat the style change as any other variable in your template:

    
    
    from flask import Flask, render_template_string
    
    app = Flask(__name__)
    
    index_page = """<html><body><h2 style="color: {{ color }}">Index page</h2></body></html>"""
    
    @app.route('/')
    def index():
        with open('/path/to/file.txt') as f:
            color = f.readlines()[-1]
        return render_template_string(index_page, color=color)
    
    if __name__ == '__main__':
        app.run()
    

If `file.txt` ends in, for example, `blue`, then the header will be blue. Same
goes for `red`, `yellow`, etc.

The fact that you're changing a CSS value instead of, perhaps, a value in a
table makes no difference to Jinja.

If, instead, you're trying to update the CSS value after the server has
rendered the page and sent it off to the client, then you need to use
JavaScript. In your backend, add an additional view to get that data from the
server:

    
    
    @app.route('/lastline')
    def last_line():
        with open('/path/to/file.txt') as f:
            color = f.readlines()[-1]
        return color
    

Access this endpoint from the client with jQuery:

    
    
    <script>
        function updateCSS() {
            $.ajax({
                url: "{{ url_for('last_line') }}",
                method: 'GET',
                success: function(data) {
                    $("#baz").css("visibility", data);
                }
            });
        }
        setInterval(updateCSS, 1000);
    </script>
    

This will check the file every 1 second and update your element's CSS
accordingly.

