Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template convert to string

Tags:

python

django

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'
like image 641
David542 Avatar asked Jan 04 '15 22:01

David542


People also ask

What does {% %} mean in Django?

This tag can be used in two ways: {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. {% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What are template tags in Django?

The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .


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

like image 65
Simeon Visser Avatar answered Oct 10 '22 20:10

Simeon Visser


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

like image 33
Sergii Shcherbak Avatar answered Oct 10 '22 18:10

Sergii Shcherbak


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  %}
like image 3
mpassad Avatar answered Oct 10 '22 19:10

mpassad