Algorithmatic
Algorithmatic

Reputation: 1882

Django - Template tags inside css file

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.

Upvotes: 6

Views: 6883

Answers (4)

Ragy
Ragy

Reputation: 1

Had the same issue, for me I had to use style tag inside base.html

<style>
@font-face {
    font-family: "Booter - Zero Zero";
    src: url('../static/fonts/Booter\ -\ Zero\ Zero.woff') format('woff'), url('../static/fonts/Booter\ -\ Zero\ Zero.woff2') format('woff2');

    font-weight: normal;
    font-style: normal;
}

.main-header {
    background-color: rgba(0, 0, 0, .6);
    background-image: url(static/images/header_background.jpg);
    background-blend-mode: multiply;
    background-size: cover;
    padding-bottom: 30px;
}

Upvotes: 0

Juan Diego Ramirez
Juan Diego Ramirez

Reputation: 499

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>

Upvotes: 1

Gabriel Ilharco
Gabriel Ilharco

Reputation: 1679

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>

Upvotes: 1

wpercy
wpercy

Reputation: 10090

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>

Upvotes: 1

Related Questions