python - 如何检查mako模板中的instanceof?

标签 python mako

我有一个变量 myvariable,我想在 Mako 模板中使用它。我希望能够在对其进行任何操作之前以某种方式检查其类型。检查此类信息的语法是什么?我知道 python 有 typeof 和 instanceof,但是 Mako 中有类似的东西吗?或者你会怎么做?

伪代码如下:

% if myvariable == 'list':
// Iterate Throuh the List
   %for item in myvariable:
         ${myvariable[item]}
   %endfor
%elif variabletype == 'int':
// ${myvariable}

%elif myvariable == 'dict':
// Do something here

最佳答案

您可以使用isinstance():

>>> from mako.template import Template
>>> print Template("${isinstance(a, int)}").render(a=1)
True
>>> print Template("${isinstance(a, list)}").render(a=[1,2,3,4])
True

UPD。 if/else/endif 内部的用法如下:

from mako.template import Template
t = Template("""
% if isinstance(a, int):
    I'm an int
% else:
    I'm a list
% endif
""")


print t.render(a=1)  # prints "I'm an int"
print t.render(a=[1,2,3,4])  # prints "I'm a list"

关于python - 如何检查mako模板中的instanceof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18599946/

相关文章:

python - 我应该使用 Mako 做模板吗?

templates - mako 和 Openlayers 之间的变量替换冲突

python 将数组拆分为运行/序列 - 最好是 numpy

python - 用于匹配导出为任务纸格式的 Omnifocus 项目的正则表达式

python - 如何查看read_csv的进度条

python - 从 Pyramid 应用程序 View 中获取 Mako 模板

python - 如何使用 Flask 设置 mako 模板以产生可破译的异常?

python - 是否有理由劝阻我在我的 Django 应用程序中使用替代模板引擎?

python - 如何比较 Debian 软件包版本?

python - 在 Django Heroku 应用程序中使用 print() 日志记录将信息记录到 Papertrail 的好处