How to use Django template tag within another tag?

筅森魡賤 提交于 2019-12-10 23:23:13

问题


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?


回答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.



来源:https://stackoverflow.com/questions/37933259/how-to-use-django-template-tag-within-another-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!