I am trying to change some variable in base html-template which other html pages inherite from after entering user in personal account.
The idea is as follows:
there is base html template and there depends on user status (logged in or logged out) are buttons
Registration
andEnter
/Exit
.if user is logged in then I want
Enter
button andRegistration
button to be dissappeared and instead ofEnter
button I wantExit
button to be therein case if user is not logged in then two buttons should be:
Enter
andRegistration
I managed to accomplish this task using flask, jinja2 and python but my backend code looks unbearably ugly because there is too much of duplication
Here is my python code:
this function executes before user gets to any html page and determines its status
from flask import g
from flask import render_template
@app.url_value_preprocessor
def send_user_login_status(endpoint, values):
if current_user.is_authenticated: # if logged in
g.login_button_class = u'logout'
g.login_button = u'Exit'
g.signin_button = u''
g.signin_button_class = u'signout'
else: # if not logged in
g.login_button_class = u'login'
g.login_button = u'Enter'
g.signin_button = u'Registration'
g.signin_button_class = u'signin'
return render_template("base.html",
login_button=g.login_button,
login_button_class=g.login_button_class,
signin_button=g.signin_button,
signin_button_class=g.signin_button_class,
)
And now I must every time pass variables to html page in order this page to be with needed buttons.
For example home page:
@app.route('/')
def home():
return render_template("index.html",
login_button=g.login_button,
login_button_class=g.login_button_class,
signin_button=g.signin_button,
signin_button_class=g.signin_button_class,
)
or about us page:
@app.route('/about')
def about():
# send_user_login_status()
return render_template("about.html",
login_button=g.login_button,
login_button_class=g.login_button_class,
signin_button=g.signin_button,
signin_button_class=g.signin_button_class,
)
This is my python logout function:
@app.route('/logout', methods=['POST'])
def logout():
login_status = logout_user()
if login_status:
g.login_button_class = u'login'
g.login_button = u'Enter'
g.signin_button = u'Registration'
g.signin_button_class = u'signin'
jsonify({'result': True})
return redirect('/')
And as you can see there is too much of duplication because I need to pass this depends-on-login-status variables to each html page.
Whereas html code looks nice:
base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
</head>
<body>
<nav id="menu">
<ul class="right">
<li class="{{ login_button_class }}"> {{ login_button }}</li>
<li class="{{ signin_button_class }}">{{ signin_button }}</li>
</ul>
</nav>
<main>
{% block content %}
{% endblock %}
</main>
</body>
index.html
{% extends "base.html" %}
{% block content %}
<h1>Home</h1>
{% endblock %}
about.html
{% extends "base.html" %}
{% block content %}
<h1>About</h1>
{% endblock %}