2012-06-02 58 views
5

有什么方法可以在django模板中有一个随机字符串?模板中的随机字符串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 %} 

编辑: 谢谢你的答案,但我的情况下,需要更具体的东西,因为它是在基本模板(至极我忘了说抱歉) 。所以爬行谷歌和一些文档后,我落在背景处理器文章至极做的工作,我发现它有点“heavey”反正只是用于生成随机数...

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

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

我没有找到一种方法来生成一个基数查看(有没有?),如果有一种方法比上下文过程更好,我会很高兴有一些信息。

回答

2

我想你想有一个标签,从一些包含字符串的表中生成随机字符串。看到这个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) 
0

你应该编写一个自定义模板标签,看看这个(具有封闭功能)为例:http://djangosnippets.org/snippets/150/,但如果它不是关键的话,对于模板中的行数组,我宁愿将这个随机字符串在视图中生成。

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

两者还可以添加这context_processors并将它全局可用。好的提示 – zzart

+0

目前为止的最佳解决方案 – codingrhythm

13

你可以做这样的事情:

{# 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/

+0

我想这只受unicode中字母数量的限制,但'with'语句真的会很快变得非常奇怪。这是值得的,但我们可以拥有'{%elif rnd =='“%}'语句 – mlissner

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

在标记。潘岳:

@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/