1

I have a django template tag that sets a context variable (it gets a random image from a model, but for this example, lets say it gets a random number)

{% get_random_number %}
{{ my_random_number }} <!-- outputs a random number between 1 and 10 -->

This works fine.

However I need to get the same 'random' number in two different blocks within my page:

{% block block1 %}
  {% get_random_number %}
  {{ my_random_number }} <!-- outputs a random number between 1 and 10 -->
{% endblock %}

{% block block2 %}
  {% get_random_number %}
  {{ my_random_number }} <!-- outputs a random number between 1 and 10 -->
{% endblock %}

This obviously doesn't work as I get two different results (unless by chance, they're the same!)

So how do you use a templatetag to set a context variable that's consistent across two template blocks?

doing this doesn't work - the context variable is limited to the block it's created in...

{% get_random_number %}

{% block block1 %}
  {{ my_random_number }}
{% endblock %}

{% block block2 %}
  {{ my_random_number }}
{% endblock %}

So.. how can I 'save' the initial result somewhere else, then recall it, if it's already been generated earlier in the call?

Thanks

2 Answers 2

4

Probably, you can use {% with %} tag

{% with my_random_number=get_random_number %}

{% block block1 %}
  {{ my_random_number }}
{% endblock %}

{% block block2 %}
  {{ my_random_number }}
{% endblock %}

{% endwith %}
Sign up to request clarification or add additional context in comments.

Comments

1

You could move your template tag logic to your view instead. In your view you would only need to call get_random_number getting 1 number, and then use that in as many places as you want in your template.

Comments

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.