Determine variable type within django template

Viewed 32591

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.

6 Answers

Late to the party, but I just had this problem. The solution I went for is duck-typing, so:

{% if action.extra_column.year %}
  {{ action.extra_column|date:"M y" }}
{% else %}
  {{ action.extra_column }}
{% endif %}

Could you argue that this is definitely not the right way to do it? Probably. Will it get the job done without writing your own template filter and having even more code to maintain? Absolutely.

You can try this to recognize String vs List type:

{%if v_1.0.1|length == 0%}
    <!--STR-->
    {{v_1}}
{%else%}     
     <!--List-->                                           
    {{v_1.0}}
{%endif%}

That's my approach:

@register.filter
def get_type(value):
    """ It returns variable type as a pure string name """
    return type(value).__name__
Related