Determine variable type within django template

前端 未结 5 1097
执念已碎
执念已碎 2020-12-03 21:02

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:

<         


        
5条回答
  •  独厮守ぢ
    2020-12-03 21:49

    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.

提交回复
热议问题