Django - string from variable inside template tag
Asked Answered
M

1

6

I can't figure out how to send multiple arguments into custom template filter.

The problem is that I use template variables as an arguments.

CUSTOM TEMPLATE FILTER

@register.filter
def is_scheduled(product_id,dayhour):
    day,hour = dayhour.split(',')
    return Product.objects.get(id=product_id).is_scheduled(day,hour)

NORMAL USE

{% if product.id|is_scheduled:"7,22" %}...{% endif %}

The line above would work correctly like I put two arguments - 7 and 22 into the filter (tested - works). The problem is that I want to put variables instead of plain text/string as an argument.

In my template:

{% with  day=forloop.counter|add:"-2" hour=forloop.parentloop.counter|add:"-2" %}

Now, I want to use {{ day }} and {{ hour }} as an arguments.

I tried for example:

{% if product.id|is_scheduled:"{{ day }},{{ hour }}" %}...{% endif %}

But this raises:

Exception Value: invalid literal for int() with base 10: '{{ day }}'

Do you have any ideas?

Meunier answered 5/11, 2016 at 17:0 Comment(0)
S
6

You don't need the {{}} when you're inside the {% %}. Just use the names directly in that tag and use the string concat template syntax add.

In case day and hour are strings, a type conversion to string will be required before concating the strings:

{% with day|stringformat:"s" as sday hour|stringformat:"s" as shour %}
    {% with sday|add:","|add:shour as arg %}
        {% if product.id|is_scheduled:arg %}...{% endif %}
    {% endwith %}
{% endwith %}
Selfassured answered 5/11, 2016 at 17:16 Comment(3)
Unfortunately, this doesn't work. I'm not sure why. Probably, day and hour are integers. It returns: Exception Value: 'int' object has no attribute 'split' and if I print dayhour variable it prints 0 instead of "0,2" for example.Meunier
Seems like a good approach but there is some problem, probably with syntax. u'with' received an invalid token: u'hour|stringformat:"s"' I'm trying to figure out what's the point of the error.Meunier
Ok, I've added string formating to the upper with ( {% with day=forloop.counter|add:"-2"|stringformat:"s" hour=forloop.parentloop.counter|add:"-2"|stringformat:"s" hours_yesterday=forloop.counter|add:"-2"|days_to_hours %} ) and it works. ThanksMeunier

© 2022 - 2024 — McMap. All rights reserved.