Python Django 模板转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27771000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:14:23  来源:igfitidea点击:

Django template convert to string

pythondjango

提问by David542

Is there a way to convert a number to a string in django's template? Or do I need to make a custom template tag. Something like:

有没有办法在django的模板中将数字转换为字符串?或者我需要制作自定义模板标签。就像是:

{{ 1|stringify }} # '1'

采纳答案by Simeon Visser

You can use stringformatto convert a variable to a string:

您可以使用stringformat将变量转换为字符串:

{{ value|stringformat:"i" }}

See documentationfor formatting options (the leading %should not be included).

请参阅格式选项的文档%不应包括前导)。

回答by Sergii Shcherbak

回答by mpassad

just create a new template tag

只需创建一个新的模板标签

from django import template

register = template.Library()


@register.filter
def to_str(value):
    """converts int to string"""
    return str(value)

and then go to your template and add in the top of the file

然后转到您的模板并添加到文件的顶部

{% load to_str %}

{ number_variable|to_str  %}