如何在另一个标签中使用Django模板标记? [英] How to use Django template tag within another tag?

查看:155
本文介绍了如何在另一个标签中使用Django模板标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django网站,我试图获得国际化。图像文件都使用两个字母的语言代码进行编码。所以当用户切换语言时,使用模板中的语言代码更新对图像文件的引用,如下所示:

  img src ={%static'website / images / contact_us _ {{LANGUAGE_CODE}}。png'%}> 

问题是,我还必须有静态内容路径的标签。什么是优雅的方式来解决这个问题?

解决方案

根据@MarAja建议,我遵循他/她的问题和解决方案这里与我的几乎相同。我发布我做了什么,所以无论谁在这个页面上有一个解决方案。在我的研究中,我没有绊倒@ MarAja的帖子。



代码是一个精确的副本,选择不使用 add 标签是因为根据Django文档,它尝试将参数转换为int,即不适用于字符串。



全部代码:

 #自定义模板标签文件名为custom_app_tags.py
从django导入模板

register = template.Library()

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

最后,使用:

  {%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'%}>

请注意,我将所有内容都包含在内,以便随时到这里的人获取正在发生的事情的完整图片。


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?

解决方案

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.

这篇关于如何在另一个标签中使用Django模板标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆