0

I am trying to create a filter with multiple parameters. I found the first answer of this link is useful, so took his idea.

However, I don't know how to create a string variable containing all values. Here is my code:

{% with amount_comments|to_string+","+limit_amount_comments|to_string as args %}
    {% if page_nr|page_not_over_amount:args %}
        <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a>
    {% endif %}
{% endwith %}

and this is to_string filter:

@register.filter(name='to_string')
def to_string(value):
    return str(value)

then page_not_over_amount filter using that args:

@register.filter(name='page_not_over_amount')
def page_not_over_amount(page_nr, args):
    if args is None:
        return False
    else:
        arg_list = [arg.strip() for arg in args.split(',')]
        comment_amount = arg_list[0]
        comment_limit = arg_list[1]
        if page_nr*comment_limit < comment_amount-comment_limit:
            return True
        else:
            return False

But I get this exception:

Could not parse some characters: amount_comments|to_string|+","+limit_amount_comments||to_string

Thanks in advance!

Abijith Mg
  • 2,647
  • 21
  • 35
Jieke Wei
  • 173
  • 2
  • 13

1 Answers1

1

I think a better approach for this is to write a custom tag. Despite this you can use the add filter to make a single string value that can be referenced as args using with tag.

{% with amount_comments|to_string|add:','|add:limit_amount_comments|to_string as args %}
 ...
{% endwith %}

Bonus:

Cleanup page_not_over_amount

@register.filter(name='page_not_over_amount')
def page_not_over_amount(page_nr, args):
    if args is None: 
       return False

    arg_list = list(map(int, args.split(',')))
    comment_amount, comment_limit = arg_list
    return page_nr * comment_limit < comment_amount - comment_limit

Use custom assignment tag

Define an identity function assign_tuple to be a simple custom assignment tag. This function with return arguments passed to it. You can go further with this.

@register.assignment_tag
def assign_tuple(*args):
    return args

@register.filter(name='page_not_over_amount')
def page_not_over_amount(page_nr, args):
    if args is not None:
        comment_amount, comment_limit = args
        if page_nr * comment_limit < comment_amount - comment_limit:
            return True
    return False

Use this tag in your template like so:

{% assign_tuple 2 3  as rarg %}
{{ 1|page_not_over_amount:rarg }}
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81