Adjust bootstrap within jinja template (Flask Framework) - flask

I would like to adjust default bootstrap class formatting within jinja template. The only thing, what I want to do, is to change the color of the h1 element. But unfortunately, it is still black.
I am using flask and render_template module.
I have following code in template:
{% extends "bootstrap/base.html" %}
{% block head %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="bootstrap_adjust.css">
{% endblock %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Hello, Vaclav!</h1>
</div>
</div>
{% endblock %}
boostrap_adjust.css looks like this:
h1{
color:blue;
}
Thank you for any advice!
Vaclav

I ll try to answer the question "how to adjust an element using a .css file instead of styling it directly?"
Go in your base.html file, i.e. the file you extend from, and in the header tag, at the end of all the other stylesheets create a Jinja2 block like so
{% block stylesheets %}
{% endblock stylesheets %}
Second step would be to call this block in your child templates and pass your .css files in there instead of passing it in the head block.
{% block stylesheets %}
<link rel="stylesheet" type="text/css" href="bootstrap_adjust.css">
{% endblock stylesheets %}
Give it a try and let us know!

I finally found working solution here:
https://stackoverflow.com/questions/34664156/flask-bootstrap-custom-theme
So in my case this works:
{% block styles %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='bootstrap_adjust.css')}}">
{% endblock %}
.css file is placed in the folder static. But be careful, static is not part of the path in filename parameter, because url_for('static') looks automatically in this folder.
Thank you all for your willing to help!

Adding a custom CSS file:
{% block styles %}
{{super()}}
<link rel="stylesheet"
href="{{url_for('.static', filename='mystyle.css')}}">
{% endblock %}
Please Read the documentation on Flask-Bootstrap and have a good understanding of super classes.
This is the Link - Flask-Bootstrap

Related

Jinja - Using a different css for each extended template

I've come across Flask-Appbuilder as it could solve my problem. I'm trying to load different css for every template where only the skeleton remains the same.
I found this solution https://flask-appbuilder.readthedocs.io/en/latest/templates.html
However it doesn't work. Not for me anyways. I used pip3 install flask-appbuilder and everything went OK. I created appbuilder directory within templates directory. Then I used:
{% extends 'appbuilder/base.html' %}
{% block head_css %}
{{ super() }}
<link rel="stylesheet" href="url_for('static',filename='css/your_css_file.css')}}">
{% endblock %}
what might be causing the problem ? It's like the block head_css is being completely ignored. Only the basic bootstrap css is being loaded.
You can have a single layout.html file extended by all templates, then use if statements to select the correct CSS style sheet for each template by accessing request.endpoint which is basically the view function that renders a template.
{% if request.endpoint == 'index' %}
<link href="{{ url_for('static', filename='main.css') }}" rel="stylesheet" type="text/css">
{% elif request.endpoint == 'another' %}
<link href="{{ url_for('static', filename='another.css') }}" rel="stylesheet" type="text/css">
{% endif %}

Do I need to use 'load static' twice on overall layout and header in Django?

I'm on a project in Django, and the problem is like this.
My site have a overall layout like 'layout.html' which includes some static files, links in and 'header.html' including navigator, 'footer.html' including some links in . But Both of 'layout.html' and 'header.html' uses static files so I think one command {% load static %} on first line in 'layout.html' can affect both 'layout.html' and 'header.html' because 'layout.html' includes 'header.html'! But it doesn't work, it works only when {% load static %} in both files.
Maybe my explanation is hard to understand, so I will write my code very shortly.
'layout.html'
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="{% static 'onepage-scroll.css' %}" rel="stylesheet" type="text/css">
</head>
<body>
{% include 'header.html' %}
{% block content %}
{% endblock %}
{% include 'footer.html' %}
</body>
</html>
'header.html'
{% load static %}
<nav id="navi">
<h3><img src="{% static 'logo.jpg' %}"></h3>
</nav>
I think this is not a good implementation because there are 2 times of loading staticfiles. Is there another way to solve this?
I think you may be misunderstanding what {% load static %} does. It just gives your template access to the associated {% static %} tag. It does not result in the static files themselves being reloaded or any significant burden in terms of extra code being ported.
You're using the tag exactly as intended. If you need static files, you need to load the tags to do that with.

Django templates, including page(s) that injects code into parent block

Is it possible to include a template (with include django template tag) within another template and "inject" some content to the page that includes (parent) through block tag, or something similar?
Let's say I have the following file structure within my project:
App/
(...)
templates/
base.html
index.html
_include1.html
_include2.html
_include3.html
_include4.html
Code for base.html:
<!DOCTYPE html>
<html>
<head lang="en">
(...)
</head>
<body>
<script type="application/javascript">
$(function () {
{% block extra_script %}
{% endblock %}
});
</script>
Code for index.html:
{% extends "base.html" %}
{% load static %}
(...)
<div class="row gutter">
<div>
{% include "_include1.html" with object=object%}
</div>
<div>
{% include "_include2.html" with object=object %}
</div>
<div>
{% include "_include3.html" with object=object %}
</div>
<div>
{% include "_include4.html" with object=object %}
</div>
</div>
And in each _include*.html I would like to call some specific JS function (for example), but I want to place it in the parents (index.html or base.html, doesn't matter in my case) extra_script block. I searched in the documentation, other questions and didn't find a way to do this with the include syntax.
I've done something similar but through extends tag. However I don't want to define a block in the index.html or base.html for each page that I need to include ({% bloc include_* %}.
So the solution that I have now (and works) is to define a script in each included page like this (_include1.html):
<div>
(...)
</div>
<script>
$(function () {
//Code that should be placed within parents script page (this is just an example)
var a = function (){
(...)
};
a();
});
</script>
However I think there's a better way to do this, by making use of django templates engine, and without having to define a block for each page that needs to be included. Also I would like to have all my js code in a single place (parents <script> tag) instead of being scattered all over the place (like it is with the presented solution).
Can anyone give some input or ideas towards this?
Thanks!
Try to use django-sekizai for that purpose.
With sekizai, you can define a JavaScript block just before the </body>:
{% render_block "js" %}
And then whenever you need to add JavaScript to that block, you write this:
{% addtoblock "js" %}
<script type="text/javascript">
// your JavaScript
</script>
{% endaddtoblock %}
If there are duplicates of the content in the {% addtoblock %} blocks, they will be used only once.

How to call several addOnLoad functions in dojo?

I'm trying to define several dojo elements from several (inherited) HTML pages , and each defines addOnLoad of his own, which causes only the latest function to be executed, since they are overridden.
Is there a way to overcome this problem?
Thanks.
You can use blocks to replace inherited elements
in template-base:
<head>
<script type="text/javascript" src=""></script>
{% block extra-header %}
#code default
...
{% endblock %}
</head>
in template:
{% block extra-header %}
{{ block.super }}
#replacement code
...
<script type="text/javascript" src=""></script>
{% endblock %}
for more information see https://docs.djangoproject.com/en/1.3/topics/templates/#template-inheritance

How do I retain the whitespace in templates' blocks?

I'm using SHPAML (HAML for python) for Django, however, I'm facing problems converting SHPAML -> HTML because of whitespace issues when overriding some blocks, heres an example:
In skeleton.shpaml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{{ title }}</title>
{% comment %}
<link rel="shortcut icon" href="/static/images/favicon.ico" type="image/x-icon"/>
{% endcomment %}
{% if css_list %}
{% for css in css_list %}
<link type="text/css" rel="stylesheet" href="{{css_relative}}{{ css }}">
{% endfor %}
{% endif %}
{% if js_list %}
{% for js in js_list %}
<script type="text/javascript" src="{{js_relative}}{{ js }}">
</script>
{% endfor %}
{% endif %}
{% if no_cache %}
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
{% endif %}
</head>
body
#nonFooter
#content
{% block header %} {% endblock %}
#maincontent
{% block content %} {% endblock %}
#footer
</html>
In index.shpaml:
{% extends "includes/skeleton.shpaml" %}
{% block content %}
asd
.test
.test2 | meh
{% endblock %}
In the end, my output is this:
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Home | Zineified</title>
<link type="text/css" rel="stylesheet" href="/media/css/base.css">
<script type="text/javascript" src="/media/js/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" src="/media/js/jquery.form.js">
</script>
<script type="text/javascript" src="/media/js/base.js">
</script>
</head>
body
#nonFooter
#content
#maincontent
asd
.test
.test2 | meh
#footer
</html>
As you can see, whitespace is not preserved in the blocks. The next line in index.shpaml goes straight down into the next line in skeleton.shpaml. How can I prevent this and retain whitespace through template extending?
It looks like the SHPAML preprocessor is not getting invoked BEFORE Django. What I typically do is write all my documents in SHPAML with a .shpaml extension, and then I convert them to Django with the .html extension, and then let Django do its magic. So you will want statements like "extends" and "include" to refer to the .html document that has already been preprocessed.
Your base shpaml doc will look something like this:
html
body
#main_page
{% block body %}
{% endblock %}
And then the document that extends it will look something like this:
{% extends 'base.html' %}
{% block body %}
p
This is a paragraph about {{ book }}...
{% endblock %}
And then you want to preprocess them BEFORE Django sees them. I usually preprocess them with a Python script right before doing "manage.py runserver."
from docs:
spaceless
Removes whitespace between HTML tags. This includes tab characters and newlines.
Example usage:
{% spaceless %}
<p>
Foo
</p>
{% endspaceless %}
This example would return this HTML:
<p>Foo</p>
Only space between tags is removed -- not space between tags and text.
You can also remove excess spaces/newlines manually, but that will reduce the readability of the template.
#maincontent
asd
You mean misalignment here? Well, align your index.shpaml accordingly:
{% extends "includes/skeleton.shpaml" %}
{% block content %}
asd
.test
.test2 | meh
{% endblock %}
I've wrote a simple script to recursively explore a directory and find all shpaml files and convert them to *.htm. Thought I'd share it:
#!/usr/bin/env python
#===============================================================================
# Recursively explore this entire directory,
# and convert all *.shpaml files to *.htm files.
#===============================================================================
import shpaml
import os, glob
count = 0
def main():
global count
cwd = os.path.dirname(os.path.abspath(__file__))
convert_and_iterate(cwd)
print("Done. Converted "+str(count)+" SHPAML files.")
def convert_and_iterate(path):
global count
for file in glob.glob(os.path.join(path,'*.shpaml')):
#getting generic name
file_basename = os.path.basename(file)
gen_name = os.path.splitext(file_basename)[0]
#opening shpaml file and converting to html
shpaml_file = open(file)
shpaml_content = shpaml_file.read()
html_content = shpaml.convert_text(shpaml_content)
#writing to *.htm
html_file = open(os.path.join(path,gen_name+".htm"),"w")
html_file.write(html_content)
#incrementing count
count += 1
#transverse into deeper directories
dir_list = os.listdir(path)
for possible_dir in dir_list:
if os.path.isdir(os.path.join(path,possible_dir)):
convert_and_iterate(os.path.join(path,possible_dir))
if __name__ == "__main__":
main()