Django template convert to string

Question:

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'
Asked By: David542

||

Answers:

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).

Answered By: Simeon Visser

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 %}
<!-- add the filter to convert the value to string-->
{% number_variable|to_str  %}
Answered By: mpassad

You can simply use some custom filters

# app/templatetags/tags.py

from django import template

register = template.Library()


@register.filter
def toInt(string):
    return int(string)


@register.filter
def toStr(integer):
    return str(integer)

Then do like this in you template

{% load tags %}
<p>Int to Str : {{ 1|toStr }}</p>
<p>Str to Int : {{ '1'|toInt }}</p>
Answered By: Al Mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.