Monday, August 31, 2015

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

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.

On Sunday, 30 August 2015 02:35:31 UTC+1, Val Neekman wrote:
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/574d56e1-a6fa-46a7-af11-63fd802e30e3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment