When running Flask normally, everything described below works absolutely fine.
When running a build in Frozen-Flask however, I run into the issue where my dynamically built route string won't allow me to concatenate a variable (containing a string) with a string for use in a url_for()
function within Jinja2. But only when the variable data is originating from Python such as render_template()
.
routes.py
@app.route('/some-route/')
def some_route():
return render_template('my_template.html', foo='bar')
base.html
{% import "includes.html" as includes %}
{{ includes.my_macro(foo) }}
includes.html
# The following does NOT work
{% macro my_macro(foo) %}
<a href="{{ url_for('index_' ~ foo) }}">Link text</a>
{% endmacro %}
Although the above runs fine in Flask, when I do a build with Frozen-Flask I get the following error:
werkzeug.routing.BuildError: Could not build url for endpoint 'index_'. Did you mean...
As you can see, the value of foo (or the string value bar
) is missing. It should have been index_bar
.
So I tried this instead:
# This also does NOT work
{% macro my_macro(foo) %}
{% set route = 'index_' ~ foo %}
<a href="{{ url_for(route) }}">Link text</a>
{% endmacro %}
The above produces the exact same error.
So I tried this to try to better understand the problem:
# This works correctly
{% macro my_macro(foo) %}
{% set route = 'index_' ~ 'bar' %}
<a href="{{ url_for(route) }}">Link text</a>
{% endmacro %}
So I further tried this:
# This also works correctly
{% macro my_macro(foo) %}
{% set foo2 = 'bar' %}
{% set route = 'index_' ~ foo2 %}
<a href="{{ url_for(route) }}">Link text</a>
{% endmacro %}
So basically, I can create a dynamic route string for use by url_for()
but only when the variable data doesn't come from the Flask routes file (such as my routes.py
), only if the variable is created within Jinja2.