Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 271
Maxime Favier Avatar asked Sep 03 '12 10:09

Maxime Favier


People also ask

Which template command makes a custom template tag filter available in template?

You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag.

How do I use custom template tags in Django?

Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.

How do I use template tags?

The <template> tag is used as a container to hold some HTML content hidden from the user when the page loads. The content inside <template> can be rendered later with a JavaScript. You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it.


1 Answers

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 %}
like image 109
Serhii Holinei Avatar answered Oct 02 '22 14:10

Serhii Holinei