newbsie
newbsie

Reputation: 115

How to use Django template tag within another tag?

I have a Django website that I'm trying to get internationalized. The image files are all encoded with the language code of two letters. So when a user switches the language, the references to image files are updated with the language code in templates as follows:

<img src="{% static 'website/images/contact_us_{{ LANGUAGE_CODE }}.png' %}">

Problem is, I have to have a tag as well for the path of static content. What is an elegant way to solve this?

Upvotes: 3

Views: 1676

Answers (1)

newbsie
newbsie

Reputation: 115

Per @MarAja suggestion, I followed his/her question and solution here which was practically identical to mine. I'm posting what I did, so whoever that lands on this page has a solution. During my research, I did not stumble upon @MarAja's post.

The code is an exact copy, and the choice not to use add tag is because according to the Django documentation, it tries to cast the arguments to an int i.e. not intended for strings.

Full code:

# Custom Template tag file named "custom_app_tags.py"
from django import template

register = template.Library()

@register.filter
def addstr(s1, s2):
    return str(s1) + str(s2)

Finally, usage:

{% load staticfiles %}
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
{% load custom_app_tags %}

<img src="{% static 'website/images/contact_us_'|addstr:LANGUAGE_CODE|addstr:'.png' %}">

Note, I included everything so that whomever gets here later, gets a complete picture of what is going on.

Upvotes: 1

Related Questions