Python中使用自定义配置的Jinja时IF条件语句不生效如何解决?
核心错误说明
- 语法标记混用:你自定义Jinja块起始符为
\BLOCK{,而非默认的{%或注释标记{#,你写的{# if ...}会被识别为注释,不会执行判断逻辑 - 输出标记误用:
\VAR{}是变量输出专用语法,仅用于需要打印变量值的位置,不能放在条件判断语句内部 - 判断语法错误:
not 'nan'是非法表达式,正确的不等判断写法为!= 'nan'
可用实现方案
你配置了line_statement_prefix = '#',优先推荐使用更简洁的行语句写法:
# if row['Climate (where PUE is located)'] != 'nan' Climate & \VAR{row['Climate (where PUE is located)']}\\ # endif
如果偏好使用块语法,采用你自定义的块标记写法即可:
\BLOCK{ if row['Climate (where PUE is located)'] != 'nan' } Climate & \VAR{row['Climate (where PUE is located)']}\\ \BLOCK{ endif }
补充说明:如果你要判断的
nan是Python原生浮点类型空值而非字符串,将判断条件替换为row['Climate (where PUE is located)'] is not nan即可;如果无法在模板上下文获取nan对象,也可以使用row['Climate (where PUE is located)'] | string != 'nan'强制转字符串后判断。
内容的提问来源于stack exchange,提问作者Mf5F
相关产品推荐
相关产品推荐

