简体   繁体   中英

Change CSS in a Jinja2 template

In a _layout.html file which I render to an HTML I have the following

<style type="text/css">
    .btn-primary { background: #cb6532; }
</style>

Since I want to make the color dynamic, in a generator.py

template = self.env.get_template('_layout.html')
with open('public/index.html', 'w+', encoding='utf-8') as file:
    html_and_css = template.render(
        button_primary_color = "#cb6532"
    )
    file.write(html_and_css)

and changed the _layout.html to

<style type="text/css">
    .btn-primary { background: {{ button_primary_color }}; }
</style>

Thing is, this way the color isn't applied, this is what I see in the generated file

<style type="text/css">
    .btn-primary { background: ; }
</style>

How can that be done?


Edit

If I change the _layout.html to

<style type="text/css">
    .btn-primary { background: "{{ button_primary_color }}"; }
</style>

then I'll get

<style type="text/css">
    .btn-primary { background: "#cb6532"; }
</style>

which ofc doesn't apply the style.

The workaround I've used was to based in this answer . Added the following script to <head>

<script>
function addCss(rule) {
    let css = document.createElement('style');
    css.type = 'text/css';
    if (css.styleSheet) css.styleSheet.cssText = rule; // Support for IE
    else css.appendChild(document.createTextNode(rule)); // Support for the rest
    document.getElementsByTagName("head")[0].appendChild(css);
}

// CSS rules
let rule  = '.btn-primary { background: {{ button_primary_color }}; }';

// Load the rules and execute after the DOM loads
window.onload = function() {addCss(rule)};
</script>

and this way it works fine.

For problems like this JS is best. If you want to generate random colors and use it. Here s code: Hello from ARMENIA :)

let chars = '0123456abcdef'.split('');

function gen(){
    let r = '';
    for(let i=0; i<6; i++){
        r += chars[Math.floor(Math.random() * chars.length)];
    }
    return r;
}


window.onload = () => {
    document.getElementsByClassName('btn-primary')[0].background = gen();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM