Answer the question
In order to leave comments, you need to log in
How to correctly declare a custom tag in Django?
Good day!
Declared a custom tag in jang but nothing happens when used. Nothing is displayed, but there are no errors either. How to correctly declare custom tags?
# app/templatetags/extratags.py
from django import template
from app.models import Product
register = template.Library()
@register.simple_tag
def get_lenta_elem():
items = Product.objects.all()
return items
{% load extratags %}
<div class="lenta-elem-container">
{% for elem in get_lenta_elem %}
<div class="lenta-elem">
<img src="{{ elem.image.url }}" alt="{{elem.name}}">
</div>
{% endfor %}
</div>
Answer the question
In order to leave comments, you need to log in
In order to make a tag available in all views, you can add it to the templates' nettings.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'builtins': 'app.templatetags.extratags' # <<<<<<<<<<<<<<<
},
},
]
def get_lenta_elem(request):
items = Product.objects.all()
return {'items': items }
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# custom context processor
'путь_к_файлу.навание_метода' # <<<<<<<<<<<<<
],
},
},
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question