有没有办法在 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 文档)
我没有找到为基本 View 生成数字的方法(有没有?),如果有比上下文过程更好的方法,我很高兴有一些信息。
最佳答案
而不是使用 if-else
块,将字符串列表传递给您的模板并使用 random
过滤器似乎更好
在您看来:
my_strings = ['string1', 'string2', ...]
...
return render_to_response('some.html', {'my_strings':my_strings})
在你的模板中:
{{ my_strings|random }}
Here is the doc .
关于django - 模板django中的随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10860984/