V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
jingslunt
V2EX  ›  程序员

Jinjia2 的 default 过滤器问题

  •  
  •   jingslunt · Oct 8, 2021 · 1270 views
    This topic created in 1670 days ago, the information mentioned may be changed or developed.

    jinjia2 的渲染模板,在 web 渲染 /ansible 渲染 /helm 渲染都有遇到过这个问题。 当 value 的值是 bool 类型的 false,就会变成了 defalut 过滤器的第二个参数。 是否存在避免这类问题更好的写法,不用去关心 value 的值类型通用的写法。

    Hey {{ value|default "there" }}
    

    官方的建议是

     Hey {{ value |default("there", true) }},
    
    Supplement 1  ·  Oct 9, 2021

    if判断就可以解决 找到了,可以这么用

    {{- if or .Values.myVar (not (hasKey .Values "myVar")) }}
    ...
    {{- end }}
    
    3 replies    2021-10-08 17:39:44 +08:00
    ipwx
        1
    ipwx  
       Oct 8, 2021
    自己写一个过滤器啊,多简单



    env.filters['default2'] = lambda v, alt: ...
    Macv1994
        2
    Macv1994  
       Oct 8, 2021
    可以自己自定义一个过滤器
    simple2025
        3
    simple2025  
       Oct 8, 2021
    jinja 其实没有必要写过滤器呀, 他支持自己写的函数呀
    直接 `{{fn_default(value, "there")}}` 不就好了码?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2574 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 10:46 · PVG 18:46 · LAX 03:46 · JFK 06:46
    ♥ Do have faith in what you're doing.