1👍
To elaborate on what others have said, using a custom template tag for this is a simple way to do it. Inclusion tags allow you to call a template tag and pass args/kwargs to them, perform logic, and then render a template with that logic for inclusion in your rendered page.
In an app directory for your project create a folder, create a dir named templatetags
, create an empty file within that named __init__.py
(Django uses this to know the file should be run on startup), and then create another file in the new dir name my_custom_tags.py
(or whatever you’d like to use). Within that-
from django.template import Library
register = Library()
@register.inclusion_tag("home/subscribe_form.html")
def subscription_form(form):
return {'form':form}
Now, in your main template:
{% load my_custom_tags %}
{# (or whatever you named your file for custom tags #}
{# where you want to include your tag, pass the form from the main template; be sure to pass your form variable from your context data #}
{% subscription_form form %}
You have rendered your form. Since you are passing the form from context, any logic performed outside the template tag is still intact. This is especially useful when you have a generic template to use for elements in multiple places but need to perform logic outside of the view (or, in Wagtail’s case, the Page/snippet logic embedded in the model).