Determine variable type within django template

django, django-templates

Solution

Like Ignacio Vazquez-Abrams pointed out in the first comment, that's not really a great way to code your logic. I would ensure that your variable has a certain type. That could be solved through an additional variable you add to the context or an object that holds the data and something that describes the type of data.

If you want to stick to your logic, a possible approach would be to write your own template filter (let's call it `date_or_string`). The filter could subclass the builtin `date` filter with the format parameter being optional. In case the parameter is passed it works like the normal `date` filter, without the parameter it simply returns the string. In a more complex scenario the filter could also do some type checking. Just an idea, i wouldn't actually put that kind of logic into the template.

Problem

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.

Original source