0

I want to display tuple data in a django template.

I want to use a syntax like the Python formated string :

print("I have %d referrers and %f cashbacks" % request.user.get_referrer_data())

In this case, request.user.get_referrer_data() is an expensive method, so I want called it only once in my template (despite the fact that I cache its result).

Do you know a template syntax that let me inject a tuple in a string ?

A code like that would be great :

{{ "I have %d referrers and %f cashbacks" | formated_string request.user.get_referrer_data() }}

1 Answer 1

1

Use {% with ...

{% with rdata=request.user.get_referrer_data %}

I have {{ rdata.0 }} referrers and {{ rdata.1 }} cashbacks

{% endwith %}

To get greater control over the formatting of the values use a filter. Django provides floatformat for float values:

{{ rdata.1|floatformat:2 }}

gives two decimal places.

Sign up to request clarification or add additional context in comments.

2 Comments

Big thanks it's perfect. It require just no spaces near = sign.
There's an alternative syntax with request.user.get_referrer_data as rdata if you want spaces. I don't think it's deprecated, though it's referred to as "old syntax" in new docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.