Pass Dynamic Value to Django url built-in

a 夏天 提交于 2020-04-18 04:43:18

问题


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?


回答1:


Have you tried the following:

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


来源:https://stackoverflow.com/questions/54187320/pass-dynamic-value-to-django-url-built-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!