Python Forum

Full Version: How can I enter 2 jinjia variables in this hyperlink?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like to insert the data from two "zipped" lists into a hyperlink. In the following code, the DATA list is what I want the user to see in the link and the NUMBER list is the variable that I would like to pass to a new route. I've tried for hours but can't seem to get the syntax right on this. Does anyone know what is wrong with this code:

 {% for data, number in zip %}
    <p><a href="{{ url_for('view_post', number={{number}}') }}">> {{data}}</a></p>
    {% endfor %}  
Thanks!
So...after about 100 different ways of trying everything, this eventually seems to have done the trick (though, I could have sworn I tried this at least twice already...)

  {% for data, number in zip %}
    <p><a href="{{url_for('view_post', number=number) }}"> {{data}}</a></p>
    {% endfor %}
The name zip is a built-in function. You should avoid the use of this name.
You could create the links with url_for in your flask application instead in your template.


Here some examples (url_for is missing):
In [12]: import jinja2

In [13]: tpl = jinja2.Template('<a href="{{ url.href }}">{{ url.text }}<a>')

In [14]: from collections import namedtuple

In [15]: Url = namedtuple("url", "href text")

In [16]: tpl.render(url=Url("http://localhost:8080/", "localhost"))
Out[16]: '<a href="http://localhost:8080/">localhost<a>'

In [17]: from typing import NamedTuple

In [18]: class Url(NamedTuple):
    ...:     href: str
    ...:     text: str
    ...:

In [19]: tpl.render(url=Url("http://localhost:8080/", "localhost"))
Out[19]: '<a href="http://localhost:8080/">localhost<a>'

In [20]: urls = [f"/a{x}" for x in range(1,6)]

In [21]: texts = [str(x) for x in range(1, 6)]

In [22]: urls_nt = [Url(url, text) for url, text in zip(urls, texts)]

In [23]: urls_nt
Out[23]:
[Url(href='/a1', text='1'),
 Url(href='/a2', text='2'),
 Url(href='/a3', text='3'),
 Url(href='/a4', text='4'),
 Url(href='/a5', text='5')]

In [24]: urls_nt[0]
Out[24]: Url(href='/a1', text='1')

In [25]: urls_nt[0].href
Out[25]: '/a1'

In [26]: urls_nt[1].href
Out[26]: '/a2'

In [27]: urls_nt[1].text
Out[27]: '2'

In [28]: tpl = jinja2.Template('{%- for url in urls %}<a href="{{ url.href }}">{{ url.text }}<a>{%- endfor %}')

In [29]: print(tpl.render(urls=urls_nt))
<a href="/a1">1<a><a href="/a2">2<a><a href="/a3">3<a><a href="/a4">4<a><a href="/a5">5<a>

In [30]: