python - 是否有等效于 python 字符串乘法函数的 django 模板?

标签 python django django-templates django-template-filters

在 python 中我可以写 "Hello"* 5 并得到

HelloHelloHelloHelloHello

有没有办法在 django 模板中做到这一点?类似于 {% multiply "Hello"5 %} 或作为过滤器 {% "Hello"|multiply:"5"%}

或者也许是“重复”循环控制?像这样的东西:

{% repeat 5 %}
Hello
{% endrepeat %}

我可以自己编写过滤器或标签,但想知道我是否可以为自己省去一些麻烦。

如果有人可以权威地说没有我需要的内置功能,那将是一个完全可以接受的答案。

最佳答案

这是另一个技巧:

{% for x in ""|ljust:"100" %}
    Hello World!
{% endfor %}

我在这里使用一个空字符串作为值,并且重复了 100 次。您还可以使用变量来确定此技巧的重复次数 :) 只需将“100”替换为变量即可。

{% for x in ""|ljust:repeat_count %}
    Hello World!
{% endfor %}

或者自己制作...

您可以很容易地制作乘法过滤器(more on making your own template tags and filters):

在已安装的应用程序中(例如,包含在您的 INSTALLED_APPS 设置中),添加一个“templatetags”模块和一个名为“string_multiply.py”的文件

所以你会得到这样的东西:

your_app
  + templatetags
  | + __init__.py
  | + string_multiply.py 
  + __init__.py
  + models.py

加上您应用中的任何其他内容...

这是你的 string_multiply.py
from django.template import Library

register = Library()

@register.filter
def multiply(string, times):
    return string * times

是的,这就是全部......

然后在你的模板中

{% load string_multiply %}

Chris Brown:
{% filter multiply:3 %}
  Yeah!
{% endfilter %}

You (x5):
{{ request.user.username|multiply:5 }}

其输出将是:

Chris Brown:
  Yeah!
  Yeah! 
  Yeah!

You (x5):
Koliber ServicesKoliber ServicesKoliber ServicesKoliber ServicesKoliber Services

关于python - 是否有等效于 python 字符串乘法函数的 django 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8536757/

相关文章:

python - 自定义仪表板的 Django 历史记录

python - Django Template does not exist 错误,尽管它显示 'file exists'

python - django模板for循环某些表行仅显示一次

python套接字和套接字服务器

c# - 为什么不使用 IEnumerable?/与 python 相比,生成器在 c# 中如何工作

python - 将Python字典中的元素移动到另一个索引

python - Django 模型属性 - 计算模型多个实例的外键数量

python - 将旋转的 xticklabels 与其各自的 xticks 对齐

javascript - Django 调试工具栏 - Prototypejs 版本

javascript - 如何在 AJAX 中传递 Django csrf token (不使用 jQuery)