Milano
Milano

Reputation: 18725

Django - string from variable inside template tag

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?

Upvotes: 6

Views: 7999

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78556

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 %}

Upvotes: 6

Related Questions