What is the best way to dynamically build and insert templatetags from data?

43 views
Skip to first unread message

Val Neekman

unread,
Aug 29, 2015, 9:35:31 PM8/29/15
to Django users
What is the best way to dynamically build and insert templatetags from some data in settings.py

# .... in settings.py
DYN_TAGS = [
    {
        'name': 'foo',
        'data': {
             'code': 200,
             'says': 'Foo here',
        }
    },
    {
        'name': 'bar',
        'data': {
             'code': 401,
             'says': 'Bar here',
        }
    }
]

# ... in:  foobar_app/__init__.py

from django.conf import settings
for tag in settings.DYN_TAGS:
   # register tags


####### The above should be equal to #########
# if we had an app called foobar_app and it had a templatetags directory
# .... in:  foobar_app/templatetags/foo.py
  @register.assignment_tag(takes_context=True)
  def foo(context):
    return {'code': 200, 'says': 'Foo here'}

# .... in:  foobar_app/templatetags/bar.py
  @register.assignment_tag(takes_context=True)
  def bar(context):
    return {'code': 401, 'says': 'Bar here'}

Please note that the data is made up to help with the question.
Django 1.8+ answers would be great.

Thanks,
Val

Bruno A.

unread,
Aug 31, 2015, 8:07:42 AM8/31/15
to Django users
Hi,

From the doc https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-custom-template-tags
Have you looked at registering one template tag with parameters? That seems to cover your example, but I appreciate it's probably much simpler than the actual use case.

Otherwise, the bit where you register your tags should, as I understand the docs, located in foobar_app/templatetags/dynamic_tags.py, next to a __init__.py.

And then the code should be something along the lines of:
from django import template
from django.conf import settings
register = template.Library()
for register in settings.DYN_TAGS:
    register.simple_tag(lambda : register['data'], name=register['name'], takes_context=True)
# In the templates:

    {% load dynamic_tags %}
    {% foo %}

I haven't tested it, but should be close enough. I would be curious on the things you try to do with that though.
Reply all
Reply to author
Forward
0 new messages