Python Forum
How can I enter 2 jinjia variables in this hyperlink?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I enter 2 jinjia variables in this hyperlink?
#3
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]:
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: How can I enter 2 jinjia variables in this hyperlink? - by DeaD_EyE - Oct-06-2020, 01:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  find a hyperlink in Gmail body python 3(imap and selenium) taomihiranga 1 8,196 Dec-30-2020, 05:31 PM
Last Post: Gamer1057
  Hyperlink Click is not working in Selenium webdriver rajeev1729 0 2,029 May-02-2020, 11:21 AM
Last Post: rajeev1729

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020