【问题标题】:How to check instanceof in mako template?如何检查 mako 模板中的 instanceof?
【发布时间】:2013-09-03 19:25:24
【问题描述】:

我有一个变量 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

【问题讨论】:

    标签: python mako


    【解决方案1】:

    你可以使用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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      相关资源
      最近更新 更多