Skip to content

Instantly share code, notes, and snippets.

@manjurulhoque
Created November 16, 2018 15:11
Show Gist options
  • Save manjurulhoque/ccf87e6769592dc0fd6d3569811a3273 to your computer and use it in GitHub Desktop.
Save manjurulhoque/ccf87e6769592dc0fd6d3569811a3273 to your computer and use it in GitHub Desktop.
djangoapp/
__init__.py
models.py
...
templatetags/
__init__.py
custom_tags.py
Note:: After adding a new template tags module, you will need to restart
the Django development server in order to use the new template tags and filters.
Before using custom template tags, you have to make them available for the template
using the {% load %} tag. As mentioned before, you need to use the name of the
Python module containing your template tags and filters.
1. Simple Tag:
We will start by creating a simple tag to retrieve the total count of objects in our model named as YourModel.
Edit the custom_tags.py file you just created and add the following code:
from django import template
register = template.Library()
from ..models import YourModel
@register.simple_tag
def any_function(id):
return YourModel.objects.count()
and in template:
{% any_function 1 as my_function %}
{% if my_function %} my_function {% endif %}
2. Inclusion Tag:
This time we are going to use an inclusion tag. Using an inclusion tag, you
can render a template with context variables returned by your template tag. Edit the custom_tags.py file and add the following code:
@register.inclusion_tag('path_to_your_html_file.html')
def any_function():
variable = YourModel.objects.order_by('-publish')[:5]
return {'variable': variable}
Notice that the function returns a dictionary of variables instead of a simple value. Inclusion tags have to return a dictionary of values that is used as the context to render the specified template. Inclusion tags return a dictionary.
3. Assignment Tag:
Finally, we are going to create an Assignment tag. Assignment tags are like simple tags but they store the result in a given variable.
Edit the custom_tags.py file and add the following import and template tag in it:
@register.assignment_tag
def any_function(count=5):
return *some database query*
The notation for assignment template tags is {% template_tag as variable %}. We can use assignment tag in our html file like below:
{% any_function as queries %}
<ul>
{% for query in queries %}
<li>
...
</li>
{% endfor %}
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment