代码之家  ›  专栏  ›  技术社区  ›  Phil

template.render()谷歌应用引擎(python)

  •  2
  • Phil  · 技术社区  · 15 年前

    为此,我使用了谷歌的webapp框架。我在get方法中使用template.render()来为我呈现模板。

    我用下面的代码为我做这个

    path = os.path.join(os.path.dirname(__file__), file_name)
    self.response.out.write(template.render(path, template_values))
    

    其中,file_name是要呈现的模板,template_values是包含要呈现的任何值的dict()。如果我没有任何想要呈现的值怎么办?我要空着过去吗 dict() 对象?对我来说,这似乎不是一个很好的解决办法。我应该用吗 template.load() 相反?

    (我在谷歌应用引擎上也找不到模板类的文档,所以我问。)

    4 回复  |  直到 15 年前
        1
  •  5
  •   mcotton    15 年前

    你可以把一本空字典传给它,它不介意。你只需要送点东西就行了。你的模板不会显示任何内容。

    template_values = {}
    
    path = os.path.join(os.path.dirname(__file__), file_name)
    self.response.out.write(template.render(path, template_values))
    
        2
  •  4
  •   Phil    15 年前

    好的,谢谢你的回答。

    我所做的是:

    def render_template(template_name, template_values=dict()):
       path = os.path.join(os.path.dirname(__file__), template_name)
       self.response.out.write(template.render(path, template_values))
    

    这似乎是我能想到的最能解决蟒蛇问题的方法。

        3
  •  1
  •   Adam Crossland    15 年前

    由于您正在呈现django模板,因此需要使用render,并且可能无法提供空字典,因为它会抱怨找不到它期望的变量,除非将每个变量引用括在%if%块中。您应该提供一个字典,其中包含模板期望的所有键,但使用空字符串作为值。

        4
  •  1
  •   Nick Johnson    15 年前

    如果没有要传递的模板变量,只需传递一个空字典。如果您在模板中使用了任何变量,那么它们的计算结果都将为“无”。

    为了使这更容易,您可以修改助手代码:

    def render_template(template_name, template_values = None):
      if template_values is None:
        template_values = {}
      path = os.path.join(os.path.dirname(__file__), template_name)
      self.response.out.write(template.render(path, template_values))