【发布时间】:2010-09-20 06:32:52
【问题描述】:
如何在 django 模板的 url templatetag 中嵌入标签?
Django 1.0,Python 2.5.2
在views.py中
def home_page_view(request):
NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"}
variables = RequestContext(request, {'NUP':NUP})
return render_to_response('home_page.html', variables)
在 home_page.html 中,如下
NUP.HOMEPAGE = {{ NUP.HOMEPAGE }}
显示为
NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view
并且以下名为 pattern 的 url 有效(如预期的那样),
url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %}
并显示为
url template tag for NUP.HOMEPAGE = /myhomepage/
但是当{{ NUP.HOMEPAGE }} 嵌入到{% url ... %} 中时,如下所示
url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %}
这会导致模板语法错误
TemplateSyntaxError at /myhomepage/
Could not parse the remainder: '}}' from '}}'
Request Method: GET
Request URL: http://localhost:8000/myhomepage/
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: '}}' from '}}'
Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529
Python Executable: C:\Python25\python.exe
Python Version: 2.5.2
我期待 {% url {{ NUP.HOMEPAGE }} %} 在运行时解析为 {% url named-url-pattern-string-for-my-home-page-view %} 并显示为 /myhomepage/。
django 不支持嵌入标签吗?
是否可以编写一个支持嵌入标签的自定义 url 模板标签来完成这项工作?
{% url {{ NUP.HOMEPAGE }} %}
【问题讨论】:
-
如果你点击显示在“已编辑”附近的时间(比如“30 分钟前”),你会得到漂亮的彩色差异
标签: python django url templates templatetag