49

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'
3
  • 3
    What would the difference be between an integer and a string in a template? The template is just text, everything is a string. Commented Jan 4, 2015 at 22:20
  • 5
    No, doing something like {% if item.type == content_type %} one would produce a true result the other would not. Commented Jan 4, 2015 at 23:44
  • 1
    @David542: You could use {% if item.type == content_type|add:0 %} to accomplish some kind of type casting. Commented Sep 15, 2016 at 10:34

3 Answers 3

100

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

Sign up to request clarification or add additional context in comments.

3 Comments

You can indeed do that, but as I note in the comment, why would you? The output of {{ value|stringformat:"i" }} is exactly the same as the output of {{ value }}.
@DanielRoseman: when writing an if statement the type does matter - so it may be needed to convert the type in the template and use that value in a comparison later.
Adding to this you cannot do something like {% with var="this is an integer: "|add:an_int_variable %} without |stringformat:"i" on the an_int_variable first.
18

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

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.