Jinja2返回"None"(无). Google App Engine模型的字符串 [英] Jinja2 returns "None" string for Google App Engine models

查看:85
本文介绍了Jinja2返回"None"(无). Google App Engine模型的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google App Engine模型,例如:

Google App Engine models, likeso:

from google.appengine.ext.db import Model

class M(Model):
    name = db.StringProperty()

然后在从Django视图调用的Jinja2模板中,以M的in实例作为m传递:

Then in a Jinja2 template called from a Django view with an in instance of M passed in as m:

The name of this M is {{ m.name }}.

在未设置name的情况下初始化m时,将打印以下内容:

When m is initialized without name being set, the following is printed:

此M的名称为无".

The name of this M is None.

期望和期望的输出(以及使用Django模板时的输出)将是/是:

The preferable and expected output (and the output when using Django templates) would be/is:

这个M的名字是.

The name of this M is .

您知道为什么会这样吗,以及如何获得首选&预期产量?

Do you know why this is happening, and how to get the preferred & expected output?

推荐答案

您可能还想考虑使用Jinja2的或" ...

You might also want to consider using Jinja2's "or"...

The name of this M is {{ m.name or ''}}.

如果为bool(m.name) == False,则将显示The name of this M is .

如果m.name == False并希望将其显示为字符串"False",则可以使用Jinja2的默认"过滤器:

If m.name == False and you want to display it as the string "False", you can use Jinja2's "default" filter:

The name of this M is {{ m.name|default('') }}

如果为m.name is None,则将显示The name of this M is .

如果为m.name == False,则将显示The name of this M is False.

如果您想使用默认过滤器,并且仍将评估为False的任何内容显示为定义的默认值,请添加一个额外的参数:

If you want to use the default filter and still have anything evaluating to False shown as your defined default value, add an extra param:

The name of this M is {{ m.name|default('', true) }}

这应该与{{ m.name or '' }}具有完全相同的效果.

This should have the exact same effect as {{ m.name or '' }}.

您可以在 Jinja2的内置过滤器参考

这篇关于Jinja2返回"None"(无). Google App Engine模型的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆