从<a> tag in Jinja2

时间:2017-11-14 23:49:14

标签: python html regex 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 个答案:

答案 0 :(得分:0)

您真的需要<a>中的完全限定网址吗?如果没有,那么这应该可以解决问题。

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

这是一个可运行的例子:

#!/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)