django模板导入url标签有更好的方法吗?

时间:2017-10-02 19:19:15

标签: django django-templates

我的目标是在页面中列出一些链接,我想知道是否有更好的方法来执行这一行代码:

<a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a>

此部分:&#39; | add:app_name | add:&#39;:&#39; | add:model_name | add:post_fix

- 如果是这样,我的想法中存在的缺陷是什么,是URL名称,还是在模板中做得太多,还是其他什么?我应该在 view.py 中使用python代码进行构造,如果是这样,你能告诉我你将如何解决这个问题吗?

a_template.html

{% for model_name in list_model_names%}
    ....
    <a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a>
    ....
{% endfor %}

url.py

from django.conf.urls import url

from . import views

app_name = 'app'
urlpatterns = [
url(r'^stone/$, view.....as_view(), name='stone_index'),
url(r'^cloud/$', view.....as_view(), name='cloud_index'),
]

views.py

from django.shortcuts import render_to_response
from django.views import View
from app.models import (Stone, Cloud)
class ThisView(View):
   template_name = 'app/a_template.html'
   models = [Stone, Cloud]
   model_names = [model._meta.model_name for model in models]
   app_name = 'app'
   post_fix = '_index'

   dict_to_template = {'app_name': app_name,
                    'list_model_name': model_names,
                    'post_fix': post_fix}

   def get(self, *args, **kwargs):
       return render_to_response(self.template_name, self.dict_to_template)

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

反转模板中的网址会更整洁

from django.urls import reverse . # Django 1.9+
# from django.core.urlresolvers import reverse # Django < 1.9

model_names = [model._meta.model_name for model in models]
app_name = 'app'
post_fix = '_index'
urls = [reverse('%s:%s%s' % (app_name, model, post_fix)) for model in model_names

然后将模型名称和网址压缩在一起,并将它们包含在模板上下文中:

models_and_urls = zip(model_names, urls)
dict_to_template = {'models_and_urls: models_and_urls}

然后,您可以遍历模板中的模型名称和网址。

{% for model_name, url in models_and_urls %}
    ....
    <a href="{{ url }}"> {{ model_name }} </a>
    ....
{% endfor %}