【问题标题】:Random string in Django templateDjango模板中的随机字符串
【发布时间】:2012-06-02 08:46:02
【问题描述】:

有什么方法可以在 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 %}

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

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

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

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

【问题讨论】:

    标签: django templates random-access


    【解决方案1】:

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

    在你看来:

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

    在你的模板中:

    {{ my_strings|random }}
    

    Here is the doc.

    【讨论】:

    • 您也可以将其添加到 context_processors 并使其在全球范围内可用。好提示
    【解决方案2】:

    你可以这样做:

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

    【讨论】:

    • 我想这仅受 unicode 中字母数量的限制,但 with 声明很快就会变得非常奇怪。这是值得的,只是为了让我们可以有声明{% elif rnd == "?" %}
    • 看到这个让我非常想念Jinja :( 谢谢你,先生
    【解决方案3】:

    我猜你想要一个标签,它可以从一些包含字符串的表中生成随机字符串。看到这个 Django sn-p:

    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)
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

        在上下文处理器中:

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

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

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

        【讨论】:

          【解决方案6】:

          在模板中:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-06-09
            • 2016-01-29
            • 2017-05-20
            • 2012-06-06
            • 2017-07-17
            • 2020-04-15
            • 1970-01-01
            • 2020-11-11
            相关资源
            最近更新 更多