Saturday, August 29, 2015

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

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20d8352b-c9e4-45ac-8e4a-628f69a21e8a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment