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

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

问题描述

我有一个变量,我将它放入一个有时是日期有时是字符串的表中.如果变量是日期,我想更改格式:

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.

推荐答案

就像 Ignacio Vazquez-Abrams 在第一条评论中指出的那样,这并不是编写逻辑代码的好方法.我会确保您的变量具有某种类型.这可以通过添加到上下文的附加变量或保存数据的对象和描述数据类型的内容来解决.

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.

如果您想坚持自己的逻辑,一种可能的方法是编写自己的模板过滤器(我们称之为 date_or_string).过滤器可以子类化内置的 date 过滤器,格式参数是可选的.如果参数被传递,它就像普通的 date 过滤器一样工作,没有参数它只是返回字符串.在更复杂的场景中,过滤器还可以进行一些类型检查.只是一个想法,我实际上不会将这种逻辑放入模板中.

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天全站免登陆