djangotemplatetag

django - how to pass multiple values to a templatetag


I am trying to pass multiple parameters to my template tag:

@register.filter
def val_color(val, min_val):
    if val >= min_val:
        return 'red'
    return 'black'

template:

{% for x in data.vals %}
    <font color="x|data.min_val|val_color">x</font>
{% endfor %}

this approach does not work. Any ideas how to do this? Note that it would be too messy if I have to convert x numbers into objects with a value and the min_val properties so I am hoping there is a proper solution for this issue.


Solution

  • It is not clear what are you trying to do. In your function I don't see any usage of min_val.

    But let me give an example how filters work. Here is example of filter tags

    @register.filter
    def keyvalue(dict, key):
        """Filter to fetch a dict's value by a variable as key"""
        return dict.get(key, '')
    

    Usage of filter tag

    {{ weekday_dict|keyvalue:var }}
    

    Here weekday_dict is dict and 'var' is key I want to access. In keyvalue filter tag weekday_dict is first argument dict and var is second argument.

    To pass multiple arguments you can refer to link

    In short you can not easily pass multiple arguments in filter tag. You can pass it as comma seperated value, or pass them using multiple filters as given by one of answeres at link

    @register.filter(name='one_more')
    def one_more(_1, _2):
        return _1, _2
    
    def your_filter(_1_2, _3)
        _1, _2 = _1_2
        print "now you have three arguments, enjoy"
    
    {{ _1|one_more:_2|your_filter:_3 }}
    

    Update: As I can seen in your updated question. You do not need to pass multiple arguments Your filter tags is defined as:

    @register.filter
    def val_color(val, min_val):
        if val >= min_val:
            return 'red'
        return 'black'
    

    To use this tag you can update your template code to

    {% for x in data.vals %}
        <font color="{{ x|val_color:data.min_val }}">{{ x }}</font>
    {% endfor %}
    

    You can also set some default value to second argument and then you don't need to pass min value for default cases. Also don't forget to load filter before using them. For more details on tags refer to link