【问题标题】:Possible to %include file in Mako whether file exists or not?无论文件是否存在,都可以在 Mako 中 %include 文件吗?
【发布时间】:2014-02-08 18:26:56
【问题描述】:

我正在使用<%include file="special_message.html" /> 在页面上包含任何必需的特殊消息(例如有关系统停机的消息)。

我希望能够通过将消息 HTML 放入 special_message.html 文件来打开消息,并通过简单地删除文件来关闭它。

但是,如果我删除该文件,Mako 将失败并显示 cannot locate template 消息。如果找不到%include 文件,是否有任何方法(不使用空文件)告诉 Mako 不包含任何内容?

【问题讨论】:

    标签: python mako


    【解决方案1】:

    这个原始的 Python 块可以解决问题...

    <%
        from mako.exceptions import TemplateLookupException
    
        try:
            tmpl = self.get_template("special_message.html")
        except TemplateLookupException:
            pass
        else:
            tmpl.render_context(context)
    %>
    

    【讨论】:

      【解决方案2】:

      使用:

      <%include file="special_message.html" />
      

      您可以通过将消息 HTML 放入文件中来打开消息

      您可以通过清除文件来关闭消息

      echo > special_message.html
      

      with open('special_message', 'w') as f:
          f.write('')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        相关资源
        最近更新 更多