模板django中的随机字符串

kol*_*llo 5 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 %}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Fal*_*gel 18

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

在你看来:

my_strings = ['string1', 'string2', ...]
...
return render_to_response('some.html', {'my_strings':my_strings})
Run Code Online (Sandbox Code Playgroud)

在您的模板中:

{{ my_strings|random }}
Run Code Online (Sandbox Code Playgroud)

这是文档.

  • 您还可以将其添加到context_processors并使其全局可用。好提示 (2认同)

Dan*_*tar 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 %}
Run Code Online (Sandbox Code Playgroud)

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

  • 我想这仅受 unicode 中字母数量的限制,但是 `with` 语句很快就会变得非常奇怪。这是值得的,因为我们可以有语句`{% elif rnd == "" %}` (2认同)

Pri*_*tel 4

我想您想要一个标签,可以从某个包含字符串的表中生成随机字符串。请参阅这个 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)
Run Code Online (Sandbox Code Playgroud)