使用 Django 为模板菜单制作自定义 URL

Making Custom URLs with Django for Template Menue

我的想法是采用我的视图地址,在我的例子中是 hikes.views.displayHike 并从我的数据库中传递不同的 ID 号,这样就会有一个由模板中的 for 循环生成的链接列表。如果我这样做:

{%block content%}   
    {% for x in data %}
        <a href="{%url hikes.views.displayHike x.hikeId:{{x.hikeId}}%}"> {{x.name}}</a>
    {% endfor %}
{%endblock%}

{%block content%}   
    {% for x in data %}
        <a href="{%url 'hikes.views.displayHike' {{x.hikeId}}%}"> {{x.name}}</a>
    {% endfor %}
{%endblock%}

以上两种观点很简单:

def hikeHome(request):
    data = Hikes.objects.all()       
    return render(request, 'hikeHome.html', {'data':data})

我收到一个语法错误:

Django Version: 1.7
Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: ':{{x.hikeId}}' from 'x.hikeId:{{x.hikeId}}'

但是,如果我硬编码这样的值:

{%block content%}   
    {% for x in data %}
        <a href="{%url 'hikes.views.displayHike' 1 %}"> {{x.name}}</a>
    {% endfor %}
{%endblock%}

它很好用,但我不想有一个硬编码值...我希望能够将它放在 for 循环中让它 运行 并为用户显示所有可能的链接.

我还尝试在视图中创建 URL,将其放入字典中并访问名称作为键和值作为 URL,如下所示:

查看:

def hikeHome(request):
    hikes = Hikes.objects.all()    
    data = dict()
    for x in hikes:
        data[x.name] = reverse(displayHike,args=[1])

    return render(request, 'hikeHome.html', {'data':data})

模板:

{%block content%}   
    {% for x, y in data.items %}
        <a href="{%url {{y}}%}"> {{x}}</a>
    {% endfor %}
{%endblock%}`

这得到错误信息:

Django Version: 1.7
Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: '{{y}}' from '{{y}}'

阅读文档 - https://docs.djangoproject.com/en/1.7/ref/templates/builtins/

{% block content %}
    {% for x in data %}
        <a href="{%url 'hikes.views.displayHike' x.hikeId %}"> {{x.name}}</a>
    {% endfor %}
{% endblock content %}

应该可以解决问题。