【问题标题】:Python - Mako templates: How to check for incoming string?Python - Mako 模板:如何检查传入的字符串?
【发布时间】:2013-09-24 20:14:02
【问题描述】:

我在 Python 项目中使用 Mako 模板。

值 None 有时会用于联系人标题。如果值为None,我想隐藏None

当前代码:

<td class="data-career request-row">
    %if 'title' in message['contact'] and 'title' is not 'None':
        ${message['contact']['title']}
    %endif
</td>

我也试过了:

%if 'title' in message['contact'] and 'title' is not None:

但是 None 仍然出现,所以我很好奇在 Mako 中检查传入字符串值的正确方法是什么?

我在他们的docs site 上找不到任何东西。

【问题讨论】:

  • %if message['contact'].get('title'): 工作吗?

标签: python string mako


【解决方案1】:

显然字符串'title' 不能是None,因为它是......好吧,'title'。 :D

%if 'title' in message['contact'] and message['contact']['title'] is not None:
    ${message['contact']['title']}
%endif

%if 'title' in message['contact']:
    ${message['contact']['title'] or ''}
%endif

或最简单/最短的

${message['contact'].get('title', None) or ''}

【讨论】:

  • 啊,非常感谢! /facepalm 很酷,想知道我是否可以在没有和if else 的情况下编写它
猜你喜欢
  • 1970-01-01
  • 2011-04-24
  • 2011-04-29
  • 1970-01-01
  • 2011-04-14
  • 2012-04-22
  • 2019-02-08
  • 1970-01-01
  • 2012-04-28
相关资源
最近更新 更多