I have global variable accessible from every HTML file. The variable is called canAccessClients
. Its a list of objects (clients) to which the logged user has access. It is mainly used in menu, so user can see only his clients. I can find the client's logo (its url) by canAccessClients.<some_index>.picture.url
.
Now, I have one page where are only some clients.
I know the ID of these clients.
This client ID is not obviously the same as index in list of canAccessClients
.
Because canAccessClients
is only a list of client objects.
Now I need to show logo for same client which I know his ID.
I do it (maybe to bad idea, but works) by finding iterating through canAccessClients
and looking for the needed ID.
{% for client in canAccessClients %}
{% if client.id == client_data.CLIENT_ID %}
<img class="client-menu-logo" src="{{ canAccessClients.{{ forloop.counter }}.picture.url }}" alt="logo">
{% endif %}
{% endfor %}
Everything works and is ok, but... I need to pass forloop.counter
variable into canAccessClients.<some_id>.picture.url
, this does not work.
How can I use variable in some other variable in path like this?
You may write your own template tag to achieve this. Example:
@register.simple_tag
def get_image_url_by_id(id):
url = Client.objects.get(pk=id).image_url # get image url from database
return url
and in template:
{% with get_image_url_by_id forloop.counter as image_url %}
{{ image_url }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.