Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine variable type within django template

I have a variable that I'm pulling into a table that sometimes is a date and sometimes is a string. If the variable is a date, I want to change the formatting:

<td>{{ action.extra_column|date:"M d" }}</td>

But if it is a string, I just want to display it as is:

<td>{{ action.extra_column }}</td>

If I try to format it and it is a string, I get no output for the variable.

How can I determine the type so that I can adjust my rendering based on type.

like image 224
Ed. Avatar asked Aug 18 '12 23:08

Ed.


People also ask

How do I display variables in Django?

Filters. You can modify variables for display by using filters. Filters look like this: {{ name|lower }} . This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase.

How do I declare a variable inside a Django template?

Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.

What will be the type of templates variable in Django settings file?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


1 Answers

You could also implement a general template filter as an equivalent to the type() builtin:

# app/templatetags/util.py
from django import template

register = template.Library()

@register.filter
def get_type(value):
    return type(value)

# template.html
{% load util %}
{% if extra_column|get_type == 'str' %}
    String
{% elif extra_column|get_type == 'datetime.date' %}
    Date
{% else %}
    Oh no!
{% endif %}

I think Ignacio and Dirk are right, however. Can't you just have two keys (you say "array", but I assume you mean "dictionary" from the fact that the items have names) called date and detail?

# views.py
...
actions = [{
    'some_property': 'some_value'
    'date': None,
    'detail': 'details'
},
{
    'some_property': 'some_value'
    'date': datetime.date.today(),
    'detail': None
}]
...

# template.html
{% for action in actions %}
<td>{% if action.date %}{{ action.date|date:"M d" }}{% endif %}{{ action.detail }}</td>
{% endfor %}

# output
<td>details</td>
<td>Aug 19</td>
like image 172
supervacuo Avatar answered Jan 17 '23 23:01

supervacuo