[英]Change CSS in a Jinja2 template
在我渲染到 HTML 的 _layout.html 文件中,我有以下内容
<style type="text/css">
.btn-primary { background: #cb6532; }
</style>
因为我想让颜色动态,在 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)
并将 _layout.html 更改为
<style type="text/css">
.btn-primary { background: {{ button_primary_color }}; }
</style>
问题是,这种方式不应用颜色,这就是我在生成的文件中看到的
<style type="text/css">
.btn-primary { background: ; }
</style>
怎么可能呢?
如果我将 _layout.html 更改为
<style type="text/css">
.btn-primary { background: "{{ button_primary_color }}"; }
</style>
然后我会得到
<style type="text/css">
.btn-primary { background: "#cb6532"; }
</style>
哪个 ofc 不应用该样式。
我使用的解决方法是基于这个答案。 将以下脚本添加到<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>
这样它就可以正常工作了。
对于这样的问题,JS 是最好的。 如果要生成随机 colors 并使用它。 这是代码:来自亚美尼亚的你好 :)
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.