0

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?

3
  • What error do you get with the original code? Commented Jan 14, 2019 at 18:53
  • @DanielRoseman I'm sorry, what do you mean with the original code? Which? Commented Jan 14, 2019 at 19:07
  • The one you show in my_template.html. You showed the error when you used with, but what happened before you did that? Commented Jan 14, 2019 at 19:09

1 Answer 1

2

Have you tried the following:

{% with link.pattern as link_pattern %}
    <li>
      <a href='{% url link_pattern id %}'>{{link.name}}</a>
    </li>
{% endwith %}
Sign up to request clarification or add additional context in comments.

5 Comments

This seems to work! i thought that the with something=something.else was the same as the with/as pattern. How do they differ exactly? Thanks man!
Glad i could help!
I haven't used with something=something.else to be honest. I just remember that every time i need to have something dynamic inside a template tag i can just cast this something as a name variable which i can use inside.
Note, OP's problem was not as vs =, it was the bizarre use of href=url 'something'.
@DanielRoseman can you explain why that is bizarre? I’m new to the django landscape and I’ve inherited that bit. What would be more typical in your view?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.