Dynamic name variable on django template

感情迁移 提交于 2019-12-20 07:20:17

问题


I'm having a problem with django. I have a dict with all my site texts for translations. For example:

term = {"level_1": "Noob",
        "level_2": "Noob 2"}

The problem is, how can I access this key on django template?

I have

img src="/images/level_{{player.level.id}}.jpg" 
    title="{{term.level??????? }}"

I tried:

title="{{term.level{{player.level.id}}}} 

but of course this didn't work.


回答1:


Django's template language is (by design) pretty dumb/restricted. In his comment, Davind Wolever points at Accessing a dict by variable in Django templates?, where an answer suggests to make a custom template tag.

I think that in your case, it is best to handle it in your view code. Instead of only passing along a player into your context, pass both the level ID and the level name.

Possibly you can even directly pass the image url and the level name? Not constructing the URL in your template makes it more readable.



来源:https://stackoverflow.com/questions/13387885/dynamic-name-variable-on-django-template

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