Maxime Favier
Maxime Favier

Reputation: 153

How to use a template filter on a custom template tag?

I have a django problem concerning template tags. I have a template tag named modal_form with 4 arguments. This template tag works perfectly with basic variables like:

{% modal_form "clients" contact_form "Contacts" "contact" %}

But it doesn't work when i try to filter a variable inside my custom template tag like:

{% modal_form "parameters" form_dict|key:parameter parameter name_dict|key:parameter %}

This custom filter works also perfectly outside the tag (this filter get the value of a dict at a specific key). I have this error:

Caught VariableDoesNotExist while rendering: Failed lookup for key [form_dict|key:parameter]

Maybe i have to write the tag in a different way to support filter inside ?

This is my code for the tag:

def modal_form(app, object_form, object_name, object_verbose_name):
    return { 'app': app, 'object_form': object_form, 'object_name': object_name, 'object_verbose_name': object_verbose_name }

register.inclusion_tag('tags/modal_form.html')(modal_form)

And my code for the filter:

def key(d, key_name):
    try:
        value = d[key_name]
    except KeyError:
        #from django.conf import settings

        #value = settings.TEMPLATE_STRING_IF_INVALID
        value = 0

    return value
key = register.filter('key', key)

Do you have any ideas ? Do you want more code ?

Thanks in advance for your answers.

Upvotes: 9

Views: 5810

Answers (1)

Serhii Holinei
Serhii Holinei

Reputation: 5864

If your tag and filter works fine separately, try to use with statement:

{% with var_one=form_dict|key:parameter var_two=name_dict|key:parameter %}
    {% modal_form "parameters" var_one parameter var_two %}
{% endwith %}

Upvotes: 10

Related Questions