确定django模板中的变量类型 [英] Determine variable type within django template

查看:403
本文介绍了确定django模板中的变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,我拉入一个表,有时是一个日期,有时是一个字符串。如果变量是日期,我想更改格式:

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

但是,如果它是一个字符串,我只想显示它:

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

如果我尝试格式化它,它是一个字符串,我没有得到变量的输出。 / p>

如何确定类型,以便我可以根据类型调整渲染。

解决方案

像Ignacio Vazquez-Abrams在第一个评论中指出,这并不是一个很好的方式来编写你的逻辑。我会确保你的变量有一定的类型。这可以通过添加到上下文中的附加变量或保存数据的对象以及描述数据类型的东西来解决。



如果你想坚持你的逻辑,一个可能的方法是编写你自己的模板过滤器(让我们称之为 date_or_string )。过滤器可以使用format参数为可选的子类化内置日期过滤器。如果参数被传递,它的工作方式与普通的日期过滤器无关,只需返回该字符串。在更复杂的情况下,过滤器也可以进行一些类型检查。只是一个想法,我不会把这种逻辑放在模板中。


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

这篇关于确定django模板中的变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆