简体   繁体   English

如果类型为none,则格式化jinja2模板?

[英]Format jinja2 template if type is none?

I am attempting to display some information back to a user. 我正在尝试向用户显示一些信息。 A phone number from a string in a database. 来自数据库中字符串的电话号码。 Each client has 3 phone numbers, cell, home, other. 每个客户都有3个电话号码,手机,家和其他。 At least one will be filled out but the others can be null. 至少要填写一​​个,但其他可以为null。

When I formatting the numbers in jinja I am getting an error for None type. 当我在Jinja中格式化数字时,出现None类型的错误。 Is there anyway to skip the formatting if the value is None? 如果值为None,是否有跳过格式的问题? here is the code.. 这是代码。

{% for entry in results %}

                                <div class="panel-heading">{{ entry.firstName }} {{ entry.lastName }}</div>
                                <div class="panel-body">
                                    <li>Email: {{ entry.email }}</li>
                                    <li>Cell Phone: {{ "%s-%s-%s" | format(entry.cellNum[0:3], entry.cellNum[3:6], entry.cellNum[6:10]) }}</li>
                                    <li>Home Phone: {{ entry.homeNum }}</li>
                                    <li>Other Phone: {{ entry.otherNum }}</li>
                                    <br>
                                    <form action="#" method="post" class="sky-form">
                                        <input type="hidden" value="{{ entry.id }}" name="firstname">
                                    <button type="submit" class="button">Select Client</button>
                                        </form>

Any thoughts? 有什么想法吗?

how about 怎么样

{% if entry.homeNum %}{{ entry.homeNum }}{% endif %}

test data before using. 使用前测试数据。

Jinja can display None types as "None". Jinja可以将None类型显示为“ None”。 So that shouldn't be the issue. 因此,这不应该成为问题。

The issue is most likely this part: 问题很可能是以下部分:

{{ "%s-%s-%s" | format(entry.cellNum[0:3], entry.cellNum[3:6], entry.cellNum[6:10]) }}

if cellNum is None or undefined etc. this will not work as it tries to reference the value. 如果cellNum为None或未定义等,则它将无法正常工作,因为它尝试引用该值。 so call a if on cellNum first. 因此, cellNumcellNum上调用if。

{% if entry.cellNum %}{{ "%s-%s-%s" | format(entry.cellNum[0:3], entry.cellNum[3:6], entry.cellNum[6:10]) }}{% endif %}

Also, I'm assuming that all your entries in results is a valid value/object to do this with, you may want to check that too. 另外,我假设results中的所有条目都是要执行此操作的有效值/对象,您可能也要检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM