Tengo algunos enlaces en la plantilla.
<ul> {% for cat in cats %} <li><a href="{% url 'c_index' cat.slug %}">{{ cat.name }}</a> {% endear %} </ul> <ul> {% for type in types %} <li><a href="{% url 'ct_index' cat.slug type.slug %}">{{ type.name }}</a> {% endear %} </ul>
Por supuesto, no puedo acceder al segundo enlace porque no puedo usar 'cat.slug' fuera del bucle {% for cat in cats %}.
Pero quiero configurar "cat.slug" en el segundo enlace sin usar {% for cat in cats %} loop.
¿Cómo puedo hacer esto? Por ejemplo, ¿usar una etiqueta de plantilla?
url(r'^c_(?P<cat>[-\w]+)/$', views.c_index, name='c_index'), url(r'^c_(?P<cat>[-\w]+)/t_(?P<type>[-\w]+)/$', views.ct_index, name='ct_index'), def c_index(request, cat): c = {} posts = Post.objects.filter(category__slug=cat) cats = Category.objects.all() c.update({ 'posts': posts, 'cats': cats, }) return render(request, 'classifieds/index.html', c) def ct_index(request, cat, type): c = {} posts = Post.objects.filter(category__slug=cat).filter(type=type) cats = Category.objects.all() types = Types.objects.all() c.update({ 'posts': posts, 'cats': cats, 'types': types, }) return render(request, 'classifieds/index.html', c)
En sus vistas, debe agregar category = Category.objects.get(slug=cat)
. Luego agregue esa variable de category
a su contexto. Luego, en su plantilla, puede acceder a esa categoría usando la variable de plantilla que definió en su contexto. Si fuera category
, su etiqueta de URL se verá así: {% url 'ct_index' category.slug type.slug %}
.