如何使翻译与Odoo中的Python 3 "format"内置方法一起使用?



从Python v3开始,格式是进行变量替换和值格式化的主要API方法。但是,Odoo仍然使用带有%s通配符的Python 2方法。

message = _('Scheduled meeting with %s') % invitee.name
# VS
message = 'Scheduled meeting with {}'.format(invitee.name)  # this is not translated

我已经看到Odoo代码的某些部分,他们使用了一些解决方法,隔离字符串。

exc = MissingError(
_("Record does not exist or has been deleted.")
+ 'nn({} {}, {} {})'.format(_('Records:'), (self - existing).ids[:6], _('User:'), self._uid)
)

但是,有谁知道是否有更方便的方式来使用 format 方法并使其与翻译一起使用?

_返回一个字符串,因此您可以直接对其调用 format。

_("{} Sequence").format(sec.code)

或者像这样:

_("{code} Sequence").format(code=invitee.code)

当您将翻译导出到PO文件中时,您应该在第二个示例中看到以下内容:

# for FR translation you should not translate the special format expression
msgid "{code} Sequence"
msgstr "{code} Séquence"

这是第一个示例:

msgid "{} Sequence"
msgstr "{} Séquence"

如果您没有看到这一点,那么Odoo必须检查_()后面一定不能跟.,因此您可以通过执行此操作来解决此问题,例如用括号将表达式括起来:

# I think + "" is not needed 
( _("{} Séquence") + "").format(sec.code)

因为在python中"this {}".format("expression")与此("this {}").format("expression")相同

最新更新