问题
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.
回答1:
I guess you want to have a tag that generates random strings from some table containing strings. See this Django snippet:
http://djangosnippets.org/snippets/286/:
# model
class Quote(models.Model):
quote = models.TextField(help_text="Enter the quote")
by = models.CharField(maxlength=30, help_text="Enter the quote author")
slug = models.SlugField(prepopulate_from=("by", "quote"), maxlength=25)
def __str__(self):
return (self.quote)
# template tag
from django import template
register = template.Library()
from website.quotes.models import Quote
@register.simple_tag
def random_quote():
"""
Returns a random quote
"""
quote = Quote.objects.order_by('?')[0]
return str(quote)
回答2:
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.
回答3:
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/
回答4:
You should write a custom template tag, see this one (with close functionality) as an example: http://djangosnippets.org/snippets/150/, but if it is not critical, to array of lines in the template, I would rather generete this random string in view.
回答5:
In case you want to include random template and have it available globally :
in context_processors:
def sample(request):
my_strings = ['string1', 'string2', ...]
return {banners: my_stirngs}
in tempale (giving that your includes are in 'inc' folder ):
{% with banners|random as template %}
{% include 'inc/'|add:template %}
{% endwith %}
回答6:
In a template:
{% random_number as rnd %}
The best 6 digits (by default) random number is: {{ rnd }}
{% random_number 9 as rnd9 %}
The best 9 digit random number is: {{ rnd9 }}
In markup.py:
@register.assignment_tag()
def random_number(length=6):
from random import randint
return randint(10**(length-1), (10**(length)-1))
Taken from https://djangosnippets.org/snippets/2984/
来源:https://stackoverflow.com/questions/10860984/random-string-in-template-django