Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/65933635/change-css-in-a-jinja2-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
322 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...