将动态值传递给内置的Django url [英] Pass Dynamic Value to Django url built-in

查看:68
本文介绍了将动态值传递给内置的Django url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个视图中,我正在维护一个词典,该词典包含一些要显示在< a> 中的数据: //docs.djangoproject.com/zh-CN/2.1/ref/templates/builtins/#url rel = nofollow noreferrer>内置Django url 内置。



my_view.py

 链接= [
{
'name':'link 1',
'pattern':'fe:upload'
},
{
'name ':'链接2',
'模式':'fe:download'
}
]

它将像这样硬编码:

 < a href = {%url' fe:upload'id%}> up< / a> 
< a href = {%url’fe:download’id%}> down< / a>

但是我一直在努力使其陷入困境



my_template.html

 < ul> 
{%for link in links%}
< li>
< a href =’{%url link.pattern id%}'> {{link.name}}< / a>
< / li>
{%endfor%}
< / ul>

我尝试过:




  • 使用 \ 和HTML实体
  • 将引号转义
  • 将href放入临时变量,例如: {%with href = url'link.pattern'%} 并收到错误:



< blockquote>

u'with'收到了无效的令牌:u'link.pattern'




如何在此循环中添加动态模式以生成锚点?


解决方案

您是否尝试过以下操作:

  {%,link.pattern为link_pattern%} 
< li>
< a href =’{%url link_pattern id%}'> {{link.name}}< / a>
< / li>
{%结尾%}


Within a view, I am maintaining a dictionary containing some data I would like to display in an <a> in a template with the Django url built-in.

my_view.py

links = [
  {
    'name': 'link 1',
    'pattern': 'fe:upload'
  },
  {
    'name': 'link 2',
    'pattern': 'fe:download'
  }
]

It will work hardcoded like this:

<a href="{% url 'fe:upload' id %}">up</a>
<a href="{% url 'fe:download' id %}">down</a>

However I'm struggling to put it into a loop

my_template.html

<ul>
  {% for link in links %}
    <li>
      <a href='{% url link.pattern id %}'>{{link.name}}</a>
    </li>
  {% endfor %}
</ul>

I have tried:

  • escaping the quotations with \ and HTML entities
  • putting the href into a temp variable, eg: {% with href=url 'link.pattern' %} and get the error:

u'with' received an invalid token: u"'link.pattern'"

how can I put a dynamic pattern into this loop to generate an anchor?

解决方案

Have you tried the following:

{% with link.pattern as link_pattern %}
    <li>
      <a href='{% url link_pattern id %}'>{{link.name}}</a>
    </li>
{% endwith %}

这篇关于将动态值传递给内置的Django url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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