Random string in template django

kollo picture kollo · Jun 2, 2012 · Viewed 9.2k times · Source

Is there any way to have a random string in a django template ?

I would like to have multiple strings displaying randomly like:

{% here generate random number rnd ?%}

{% if rnd == 1 %}
  {% trans "hello my name is john" %}
{% endif %}

{% if rnd == 2 %}
  {% trans "hello my name is bill" %}
{% endif %}

EDIT: Thanks for answer but my case needed something more specific as it was in the base template (wich I forgot to mention sorry ) . So after crawling google and some doc I fall on context processor article wich did the job, I found it a little bit "heavey" anyway just for generating a random number...

here is the blog page : http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

Template tag did not the trick (or i did not find how) as it return a tag that cannot be translated as I remember (see blocktrans doc)

I did not find a way to generate a number for the base view (is there any ?) and if there is a way better than context process i'd be glad to have some infos.

Answer

FallenAngel picture FallenAngel · Jun 2, 2012

Instead of using if-else blocks, passing a list of strings to your template and using random filter seems better

In your view:

my_strings = ['string1', 'string2', ...]
...
return render_to_response('some.html', {'my_strings':my_strings})

And in your template:

{{ my_strings|random }}

Here is the doc.