在 Django 模板中使用字符串文字作为模板标签的参数 [英] Using string literals as parameters to template tags in Django templates
问题描述
我发现自己经常做的一件事是将字符串文字作为参数传递给模板标签或函数;例如:
One of the things I find myself doing often is passing string literals as parameters to template tags or functions; for instance:
{% url my-url 'my_param' %}
不幸的是,django 模板引擎不允许您这样做.所以我发现自己在视图代码中做了很多事情:
Unfortunately, the django template engine doesn't let you do this. So I find myself doing this a lot in my view code:
my_context_dict['MY_PARAM'] = 'my_param'
然后在我的视图代码中:
and then in my view code:
{% url my-url MY_PARAM %}
或者创建一系列 URL 映射,我个人尽量避免.
Or creating a series of URL mappings, which I personally try to avoid.
是否可以在 Django 模板中使用字符串文字?或者可能是一个更优雅的解决方案?我在此处或文档中没有看到任何内容.
Is it possible to use a string literal in Django templates? Or possibly a more elegant solution? I haven't seen anything on here or in the documentation.
推荐答案
这个感觉不对,但是是对的.
This feels wrong but is right.
<a href="{% url someting "param1" "param2" %}">text</a>
嵌套的 ""
似乎不应该工作.他们是这样.Django {% %}
材料只是从 HTML 中提取出来,而不考虑周围的上下文.所以重复"的 "
根本就不是重复的.
The nested ""
's don't seem like they should work. They do. The Django {% %}
material is simply pulled out of the HTML without regard for surrounding context. So the "duplicated" "
's aren't really duplicated at all.
这篇关于在 Django 模板中使用字符串文字作为模板标签的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!