3

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?

newbsie
  • 115
  • 7
  • 1
    Already discussed in http://stackoverflow.com/questions/37893356/passing-a-variable-to-display-in-django-template/37893421#37893421 - you have t o pass it from your view and then you can use it – dmitryro Jun 20 '16 at 23:22
  • I had the same problem, you can also check [my question](http://stackoverflow.com/questions/37574585/django-insert-image-in-a-template-whose-path-is-dynamic) and the associated answers. – MarAja Jun 21 '16 at 08:49
  • @dmitryro I don't think his problem is about passing data to the view. I think he got this point. His problem is more about using "a template tag in a static tag" (which actually does not seem possible). He should use the |add function according to the answers I got on my similar question (see above for detail) – MarAja Jun 21 '16 at 08:59
  • You create a custom template tag , load it {% load your_tags %} and use it {% your_tag|code %} and this will solve problems all together https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/ – dmitryro Jun 21 '16 at 11:57
  • Problem is resolved thanks to everyone's contribution! :) – newbsie Jun 21 '16 at 19:37

1 Answers1

1

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.

Community
  • 1
  • 1
newbsie
  • 115
  • 7