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'
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).
You can use {{ value|slugify }}
(https://docs.djangoproject.com/en/1.10/ref/templates/builtins/).
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 %}
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>
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'
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).
You can use {{ value|slugify }}
(https://docs.djangoproject.com/en/1.10/ref/templates/builtins/).
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 %}
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>