Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Template tags inside css file

Tags:

python

css

django

I'm trying to modify the css of a page based on the PageSetting model that I'm using. I'm allowing the user the ability to change how the theme of a page looks like based on some of the PageSetting attributes.

class PageSettings(SingletonModel):
    theme = models.IntegerField(choices=THEMES,
                                verbose_name=_("Theme"),
                                default=0)
    base_color = RGBColorField(blank=False,
                               verbose_name=_("Base color"),
                               default="bc0000")

    ...

What I would like to do is change some values in my css depending on base_color. Pretty much something like this:

# inside my_theme.css
.side-bar {
  background: {{ pagesetting.base_color }};
  float:left;
  width: {{ pagesetting.sidebar_width}}%

  ...

}

is this acheivble in Django? I know I can do

<div class="sidebar" style='background-color:#{{pagesetting.base_color}};'>

but this makes my html ugly and harder to debug.

like image 536
Algorithmatic Avatar asked Dec 21 '15 23:12

Algorithmatic


3 Answers

You could do it within a <style></style> tag in your view file

<style>
    .side-bar {
       background: {{ pagesetting.base_color }};
       float:left;
       width: {{ pagesetting.sidebar_width }};

       ...

    }
</stlye>
like image 186
wpercy Avatar answered Oct 08 '22 16:10

wpercy


There is no way to modify the css itself, you'll have to set the properties in the html. I believe a good way to do so is to add a predefined css class to your element. That is, in your css, you'll have one class for each style you want, and you'll add the one you want in your html.

Code example:

<div class={{ my_style_class_red }}>
 ....
</div>

Edit: if you have a large number of options (for example, if you want to customize the size of an element), you should use the <style> tag and modify its parameters with your python variables.

Code example:

<style>
   h1 {color:{{my_color}};}
   p {color:blue;font-size:{{my_font_size}};}
</style>
like image 45
Gabriel Ilharco Avatar answered Oct 08 '22 15:10

Gabriel Ilharco


do it in label <style> but use "var" in css, so your html does not detect errors

<style>
  :root {
    --color: {{object.color}};
  }
  li:before{
    content: "\2022";
    color: var(--color);

  }
</style>
like image 24
Juan Diego Ramirez Avatar answered Oct 08 '22 14:10

Juan Diego Ramirez