'Frozen-Flask, url_for() in Jinja2 and string concatenation during build
When running Flask normally, everything described below works absolutely fine. When running a build in Frozen-Flask however, I run into the following issue:
In my Jinja2 template I tried this at first, where I'm having to create the route strings of many url_for()
functions from multiple sources:
{% macro my_macro(foo) %}
<a href="{{ url_for('index_' ~ foo) }}">Link text</a>
{% endmacro %}
Although this 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
is missing.
So I thought that's annoying, but maybe the string concatenation of 'index_' ~ foo
happens after the url_for()
is parsed. So to test my theory, I tried this instead:
{% macro my_macro(foo) %}
{% set route = 'index_' ~ foo %}
<a href="{{ url_for(route) }}">Link text</a>
{% endmacro %}
But I get the exact same error. Exactly. So, as if it's setting the value of set route
before concatenating the value of the foo
variable onto the end of 'index_'
, and passing that incomplete value through to url_for()
.
However, if I substitute foo
for 'foo'
(so now foo is a string not a variable) then the concatenation works fine. So I can't concatenate string with string variables in Frozen-Flask?
Is there any way around this or is this maybe a possible bug in Frozen-Flask?
Update: It appears to be an issue with data coming from routes.py
where I have return render_template('my_template.html', foo='bar')
. This foo
variable, although it is being passed through to the base template where in turn it is passed through to the macro (it can be output to prove the data present and correct) this data however cannot, it seems, be used to dynamically create a route for use by url_for().
Solution 1:[1]
i think will help you a simple line code
<a href="{{url_for('user')}}/{{foo}}">Link Text</a>
considering foo as string only will be concatenate, no with string1+strin2, only using html printing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rodolfo Merlo Ali |