How to render a template with dynamic CSS?

后端 未结 3 1216
旧巷少年郎
旧巷少年郎 2021-01-12 08:27

I want to create a dynamic CSS file in a view and then render a template which loads that CSS file. Depending on the arguments given to the view, the CSS may have different

相关标签:
3条回答
  • 2021-01-12 08:59

    I went with @CatPlusPlus's suggestion: Calculating the necessary values in a view and passing the template a very long string (raw) which contains the entire CSS. In the template, I include it like so:

    <style media="screen">{{ raw|safe }}</style>
    

    Thanks everyone for your efforts!

    0 讨论(0)
  • 2021-01-12 09:03

    views.py:

    def create_css_file(request, color):
        f = color
        return render_to_response('mytemplate.html', locals())
    

    template:

    <body style = "color:{{f}}!important;">
    

    Don't create css file on the fly it is unnecessary.

    0 讨论(0)
  • 2021-01-12 09:17

    If you absolutely need to you can just create a css file dynamically.

    You can create an entry in your urls.py. You can name urls anything you want this could look like a static .css file to the outside world but would be created dynamically.

    (r'^(?P<color>[0-9a-f]{6})/dynamic.css$', dynamic_css)
    
    
    def dynamic_css(request, color):
       """
       Create a css file based on a color criteria,
       or any other complicated calculations necessary
       """
       # do custom element positionting.
       return render_to_response('dynamic.css', {'color': color})
    
    
    # dynamic.css    
    body {
      background-color: {{ color }}
    }
    

    There is no reason to write css files for this. Now you can just include

    <link rel="styleshee" type="text/css" href="/purple/dymamic.css" />

    In your template.

    As mentioned this shouldn't be used just for changing one color. That could be done in your template. If you had to do something like this it would probably be a good idea to implement cacheing as every time a page is requested it has to dynamically generate .css that could be performance overhead. This is more of an example to show you can name urls.py entries anything you want. And include them in any way you want in html ie. if you needed a custom javascript file dynamically created you could create an entry in urls.py and then create a view that generates a .js file.

    0 讨论(0)
提交回复
热议问题