Modifying part of the url from a <a> tag in Jinja2

I am using Jinja2, and I have an url:

http://mywebsite/blog/en/

Just below the header I have three buttons, which are intended to send to the current url, but replacing the last part with the current language. This buttons are rendered by a macro:

{% macro Languages(name='', value='', abbreviation='') %}
<button class="Languages">
    <a href="{{name}}">{{name}}</a>
</button>
{{ caller() }}
{% endmacro %}

So at the end I have something like:

<button class="Languages">
    <a href="en">English</a>
</button>
<button class="Languages">
    <a href="de">Deutsch</a>
</button>
<button class="Languages">
    <a href="es">Español</a>
</button>

My question is about how to do this. Is it possible to use some kind of regex to say something like «go to the current url but replacing the text between the last / and / for an «en» or an «es» or a «de»? I imagine that it should look like \/\w\w\/, but I can't imagine how set this in the href=''.

Thanks in advance!

1 answer

  • answered 2017-11-14 23:52 Robᵩ

    Do you really need a fully-qualified URL in your <a>? If not, then this should do the trick.

    <a href="../{{abbreviation}}">{{name}}</a>
    

    Here it is in a runnable example:

    #!/usr/bin/env python
    
    from flask import Flask, request, render_template_string
    app = Flask(__name__)
    
    @app.route('/blog/<lang>/')
    def blog(lang):
        return render_template_string('''
            {% macro Languages(name='', value='', abbreviation='') %}
            <button class="Languages">
                <a href="../{{abbreviation}}/">{{name}}</a>
            </button>
            {% endmacro %}
            <html><body><form method="post">
                {{Languages('English', '1', 'en')}}
                {{Languages('Spanish', '1', 'es')}}
                {{Languages('French', '1', 'fr')}}
                </form>
    
                <br>{{lang}} {{ {"en": "hello", "fr": "bon jour", "es": "hola"}[lang] }}
            </body></html>''', lang=lang)
    
    if __name__=='__main__':
        app.run(debug=True, port=8080)