Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random string in template django

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 (which I forgot to mention sorry ). So after crawling Google and some docs I fall on context processor article which did the job, I found it a little bit "heavy" 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 info.

like image 849
kollo Avatar asked Jun 02 '12 08:06

kollo


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .


2 Answers

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.

like image 128
FallenAngel Avatar answered Sep 30 '22 08:09

FallenAngel


You could do something like that:

{# set either "1" or "2" to rnd, "12"|make_list outputs the list [u"1", u"2"] #}
{# and random chooses one item randomly out of this list #}

{% with rnd="12"|make_list|random %}
    {% if rnd == "1" %}
        {% trans "hello my name is john" %}
    {% elif rnd == "2" %}
        {% trans "hello my name is bill" %}
    {% endif %}
{% endwith %}

Look at the "Built-in template tags and filters" documentation for more info: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/

like image 22
DanEEStar Avatar answered Sep 30 '22 09:09

DanEEStar