简体   繁体   English

在Mako模板中使用__future__导入

[英]Using from __future__ import in Mako template

I have 我有

<%!
    from __future__ import division
%>

at the very top of my template file. 在我的模板文件的最顶部。 I get the error: 我收到错误:

SyntaxError: from __future__ imports must occur at the beginning of the file 

What's the correct way to do this? 这样做的正确方法是什么?

You cannot use from __future__ import statements in Mako templates. 您不能在Mako模板中使用from __future__ import语句。 At all. 完全没有。

This is because a Mako template is compiled to a python file, and in order for this to work it sets up some initial structures at the top of that python file: 这是因为Mako模板被编译为python文件,为了使其工作,它在该python文件的顶部设置了一些初始结构:

# -*- encoding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 7
_modified_time = 1348257499.1626351
_template_filename = '/tmp/mako.txt'
_template_uri = '/tmp/mako.txt'
_source_encoding = 'ascii'
_exports = []

Only after this initial setup is any code from the template itself included. 只有初始设置之后才包含模板本身的任何代码。 Your from __future__ import division will never be placed first. from __future__ import division永远不会被放在首位。

You can still use floating point division by casting either operand of the / division operator to a float: 您仍然可以通过将/ division运算符的操作数强制转换为float来使用浮点除法:

>>> 1 / 2
0
>>> float(1) / 2
0.5

As long as you follow that workaround you can do fine without the division future import. 只要您遵循该解决方法,您就可以在没有division未来导入的情况下做得很好。

Importing from __future__ would be tidy, but I can't think of how to make it work __future__导入将是整洁的,但我想不出如何使其工作 (maybe someone who's more familiar with Mako's internals can) (也许对Mako的内部人员更熟悉的人可以) . Martijn explains why it isn't possible. Martijn解释了为什么不可能。 I can suggest a couple of work around though. 我可以建议一些工作。

If possible, do the division outside of the the template and put the result in the Context. 如果可能,请在模板外部进行除法,并将结果放在上下文中。 This aligns with my personal preference to keep as much logic out of the template as possible. 这符合我个人的偏好,以尽可能多地保留模板之外的逻辑。

If that's not an option there's the hacky solution, convert your operands to floats. 如果这不是一个选项,那就是hacky解决方案,将操作数转换为浮点数。 If you need to do this division in a bunch of different places you can add a function in a module level block: 如果你需要在一堆不同的地方进行这种划分,你可以在模块级块中添加一个函数:

<%!
    def div(a, b):
        return float(a) / float(b)
%>

Definitely less elegant than what you had in mind, but it'll work. 绝对不如你想象的那么优雅,但它会起作用。

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

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