在Django模板中使用字符串文字作为模板标记的参数 [英] Using string literals as parameters to template tags in Django templates

查看:459
本文介绍了在Django模板中使用字符串文字作为模板标记的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己经常做的一件事是将字符串文字作为参数传递给模板标签或函数;例如:

  {%url my-url'my_param'%} 
/ pre>

不幸的是,django模板引擎不允许你这样做。所以我发现自己在我的视图代码中做了很多:

  my_context_dict ['MY_PARAM'] ='my_param'

然后在我的查看代码中:

  {%url my-url MY_PARAM%} 

或创建一系列URL个人个人的URL映射。



可以在Django模板中使用字符串文字吗?或者可能是更优雅的解决方案?我没有在这里或文档中看到任何东西。

解决方案

这感觉错误但是正确。 b
$ b

 < a href ={%url sometingparam1param2%}> text< / a> 

嵌套的似乎他们应该工作。他们是这样。 Django {%%} 材质简单地从HTML中拉出,而不考虑周围的上下文。所以重复的根本没有真正重复。


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

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

Or creating a series of URL mappings, which I personally try to avoid.

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>

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屋!

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