David542
David542

Reputation: 110173

Django template convert to string

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:

{{ 1|stringify }} # '1'

Upvotes: 49

Views: 76477

Answers (3)

mpassad
mpassad

Reputation: 91

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

Upvotes: 4

Sergii Shcherbak
Sergii Shcherbak

Reputation: 977

You can use {{ value|slugify }} (https://docs.djangoproject.com/en/1.10/ref/templates/builtins/).

Upvotes: 18

Simeon Visser
Simeon Visser

Reputation: 122376

You can use stringformat to convert a variable to a string:

{{ value|stringformat:"i" }}

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

Upvotes: 98

Related Questions