django 模板上的动态名称变量 [英] Dynamic name variable on django template

查看:29
本文介绍了django 模板上的动态名称变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Django 时遇到问题.我有一个包含我所有网站文本的字典用于翻译.例如:

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"}

问题是,我怎样才能在 django 模板上访问这个键?

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

我有

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

我试过:

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

但这当然没用.

推荐答案

Django 的模板语言(按设计)非常愚蠢/受限.在他的评论中,Davind Wolever 指出 在 Django 模板中通过变量访问字典?,其中的答案建议制作自定义模板标签.

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.

我认为在您的情况下,最好在您的视图代码中处理它.不是只将 player 传递到您的上下文中,而是传递级别 ID 和级别名称.

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.

也许你甚至可以直接传递图片网址和关卡名称?不在模板中构建 URL 会使其更具可读性.

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

这篇关于django 模板上的动态名称变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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