How to write custom template tags in Django easily?
-
04-12-2019 - |
Frage
Writing template tags isn't easy in Django and involves lots of boilerplate code. What is the least painful way to do it?
- Are there any libs for that?
- Are there any tricks that doesn't involve third-party apps?
- What is your way to do it?
(I will make this post a community wiki once I figure how to do it.)
Lösung 2
There are some libs for that:
-
Used it before. Makes everythings simpler, but I couldn't figure how to handle lots of optional arguments with it.
Usage example::
''' {% example_tag for val as asvar %} ''' @tag(register, [ Constant("for"), Variable(), Optional([Constant("as"), Name()]), ]) def example_tag(context, val, asvar=None): if asvar: context[asvar] = val return "" else: return val
django-tagcon, abandoned by original author
django-ttag, fork of django-tagcon
These two look promising because of class-based approach and keyword arguments support (like
{% output limit=some_limit|default:1 offset=profile.offset %}
)Example usage::
class Welcome(ttag.Tag): ''' {% welcome current_user fallback "Hello, anonymous." %} ''' user = ttag.Arg(positional=True) fallback = ttag.Arg(default='Hi!') def output(self, data) name = data['user'].get_full_name() if name: return 'Hi, %s!' % name return data['fallback']
Andere Tipps
Try django-classy-tags https://github.com/ojii/django-classy-tags
I use the fancy_tag decorator: http://pypi.python.org/pypi/fancy_tag
Very simple and powerful and it comes with good documentation.
Gets rid of all that boilerplate when you just want to assign the output of a template tag to a context variable. Also handles (variable length) arguments and keyword arguments.
Much easier to use than for example django-templatetag-sugar.
I haven't really needed anything else apart from the built in inclusion tag decorator.