[Answer]-Django template tags within tags? trying to cut down on template logic

1👍

✅

To call an arbitrary method of any object create a simple custom template tag:

from django import template

register = template.Library()

@register.simple_tag
def call_method(obj, method_name, *args):
    method = getattr(obj, method_name)
    return method(*args)

And then call it in the template:

{% load my_tags %}

{# equivalent of `somevar.x_foo1_y()` #}
{% call_method somevar 'x_foo1_y' %}

{# equivalent of `somevar.x_foo1_y('test')` #}
{% call_method somevar 'x_foo1_y' 'test' %}

{# equivalent of `somevar.x_foo1_y(othervar)` #}
{% call_method somevar 'x_foo1_y' othervar %}

{# equivalent of `somevar.x_foo1_y()` if `method_name == 'x_foo1_y'` #}
{% call_method somevar method_name %}

And, at last, equivalent of your {% if %} expression:

{# make the `x_{{ x }}_y` method name #}
{% with 'x_'|add:x|add:"_y" as method_name %}
    {% call_method somebar method_name %}
{% endwith %}

0👍

I’m not sure what would x_foo1_y and x_foo2_y be, but I’m guessing you are generalising and asking how to handle situations like this. As such, I would suggest you use custom template tags, which might help in reducing your template logic by delegating some of it. Template tags can do pretty much anything, so I believe you could move lots of logic like this.

Leave a comment