Reputation: 46
Hello it is a pleasure to greet you, today I come to ask you for help with an error that Babel de Flask is presenting to me, I am new to the subject, but in advance I thank you for your collaboration.
At the end of the code I show in a Quote the error message.
Next the code used.
My adds init.py
import os
from flask import Flask, request
from werkzeug.datastructures import ImmutableDict
import flask_babel as babel
from flask_babel import gettext as _
b = babel.Babel()
app = Flask(__name__, instance_relative_config=True)
b.init_app(app)
@babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = session['language']
except KeyError:
language = None
if language is not None:
return language
return request.accept_languages.best_match(passbyte.config['LANGUAGES'].keys())
@app.route('/language/<language>')
def set_language(language=None):
session['language'] = language
return redirect(url_for('home'))
@app.context_processor
def inject_conf_var():
return dict(AVAILABLE_LANGUAGES=app.config['LANGUAGES'], CURRENT_LANGUAGE=session.get('language',request.accept_languages.best_match(app.config['LANGUAGES'].keys())))
My > config.py
# -*- coding: utf-8 -*-
# ...
# available languages
LANGUAGES = {
'en': 'English',
'es': 'Español'
}
My base.html
{% for language in AVAILABLE_LANGUAGES.items() %}
{% if CURRENT_LANGUAGE == language[0] or (CURRENT_LANGUAGE == '' and BEST_MATCH_LANGUAGE == language[0]) %}
<li class="lang_active"><a name="language">{{ language[1] }}</a></li>
{% else %}
<li class="lang_inactive"><a href="?lang={{ language[0] }}">{{ language[1] }}</a></li>
{% endif %}
{% endfor %}
The error
jinja2.exceptions.UndefinedError: 'AVAILABLE_LANGUAGES' is undefined
I see my code here
Upvotes: 2
Views: 2284
Reputation: 612
@babel.localselector
should be @b.localselector
.
Explanation: You created an app
object from Flask()
, the decorators use the app
object not Flask
directly, then you should do the same with babel. You created a b
(babel object), so use it.
It seems also that you do not load the configuration. Then, the app.config[*] probably returns None
. So you need to load it somewhere:
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('yourapplication.default_settings')
# or
app.config.from_pyfile('application.cfg', silent=True)
Look the official documentation for more details depending on your case: Configuration Handling
Upvotes: 2