Home > Blockchain >  Can you parameterize a template tag library on template directory?
Can you parameterize a template tag library on template directory?

Time:11-09

Let's say I'm writing a form template tag library for Django, but want to be able to render both Bootstrap and UIKit forms.

The Python code will be identical, except for the template reference. Simplified

@register.inclusion_tag('myforms/bootstrap/formrow.html')
def form_row(fieldname, labelpos, labelsize, widgetsize):
    return {...}

vs.

@register.inclusion_tag('myforms/uikit/formrow.html')
def form_row(fieldname, labelpos, labelsize, widgetsize):
    return {...}

I would like to prevent the duplication of the python code, but the @register.inclusion_tag(..) function runs very early in the Django lifecycle, so I'm not sure if it is possible, or how to do it..?

CodePudding user response:

From the documentation it's possible to register the inclusion tag using a django.template.Template instance, which means that you can do the following,

# Pseudo code
from django.template.loader import get_template

bootstrap = get_template('myforms/bootstrap/formrow.html')
uikit = get_template('myforms/uikit/formrow.html')

register.inclusion_tag(bootstrap)(re_usable_form_row_function)
register.inclusion_tag(uikit)(re_usable_form_row_function)
  • Related