模板django中的随机字符串

时间:2012-06-02 08:46:02

标签: django templates random-access

有没有办法在django模板中有一个随机字符串?

我想要随机显示多个​​字符串,如:

{% 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 %}

编辑: 感谢您的回答,但我的案例需要更具体的内容,因为它在基本模板中(我忘了提及抱歉)。因此,在抓取谷歌和一些文档之后,我依赖于上下文处理器文章做了这个工作,我发现它有点“重要”,无论如何只是为了生成一个随机数...

这是博客页面:http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

模板标签不是技巧(或者我没有找到),因为它返回一个无法翻译的标签,我记得(参见blocktrans doc)

我没有找到为基本视图生成数字的方法(有没有?)如果有比上下文过程更好的方法我会很高兴有一些信息。

6 个答案:

答案 0 :(得分:17)

而不是使用if-else块,将字符串列表传递到模板并使用random过滤器似乎更好

在您看来:

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

在你的模板中:

{{ my_strings|random }}

Here is the doc

答案 1 :(得分:14)

你可以这样做:

{# 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 %}

有关详情,请参阅“内置模板标记和过滤器”文档: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/

答案 2 :(得分:3)

我想你想要一个标签,从一些包含字符串的表中生成随机字符串。看到这个Django片段:

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)

答案 3 :(得分:0)

您应该编写一个自定义模板标记,请参阅此标记(具有关闭功能)作为示例:http://djangosnippets.org/snippets/150/,但如果它不重要,则对于模板中的行数组,我宁愿生成此随机视野中的字符串。

答案 4 :(得分:0)

如果您想要包含随机模板并让其全局可用:

在context_processors中:

def sample(request):
  my_strings = ['string1', 'string2', ...]
  return {banners: my_stirngs}

在tempale中(假设您的包含在'inc'文件夹中):

  {% with banners|random as template %}
    {% include 'inc/'|add:template %}
  {% endwith %}  

答案 5 :(得分:0)

在模板中:

{% 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 }}

在markup.py中:

@register.assignment_tag()
def random_number(length=6):
    from random import randint
    return randint(10**(length-1), (10**(length)-1))

取自https://djangosnippets.org/snippets/2984/