且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当变量为None时,Django设置为默认模板标签输出?

更新时间:2022-03-25 07:20:56

没有这样的东西存在。这就是为什么 默认值 存在default_if_none 过滤器。这是一个功能;它让你想到你在做什么,而不是依赖于一些常常会误导的行为。如果有一个变量为 None 的潜力,那么您应该计划该应急计划。如果该变量应始终具有一些值,则无表示某事不正确。如果默认是仅渲染一个空白字符串,那么您不知道该值是否未定义,或者实际上是一个空白字符串。写出一致的代码,并忘记快捷方式。

No such thing exists. That's why the default and default_if_none filters exist. This is a feature; it makes you think about what you're doing instead of relying on some behavior that would often times be misleading. If there's a potential for a variable to be None, then you should plan for that contingency. If the variable should always have some value, then the "None" indicates something is not right. If the default was to just render a blank string, then you would not know whether the value is not defined or is actually a blank string. Write coherent code and forget about shortcuts.