【问题标题】:How to integrate pystache with pyramid?如何将 pystache 与金字塔集成?
【发布时间】:2012-06-01 20:55:43
【问题描述】:

我想在我的金字塔应用程序中使用 pystache 提供的基于类的视图,但我不完全确定如何正确集成这两者。我已经读过this,但它并没有谈到使用基于类的视图。

如果我想使用基于类的视图,如何为 pystache 创建新的渲染器?有人可以帮我吗?

另外,虽然我已经知道 mustache 是如何工作的,但我似乎无法找到关于 python 实现 (pystache) 的太多信息。有人可以在这里指出我正确的方向吗?

【问题讨论】:

    标签: python template-engine pyramid mustache


    【解决方案1】:

    实现MustacheRendererFactory:

    class MustacheRendererFactory(object):
      def __init__(self, info):
        self.info = info
    
      def __call__(self, value, system):
        package, filename = resolve_asset_spec(self.info.name)
        template = os.path.join(package_path(self.info.package), filename)
        template_fh = open(template)
        template_stream = template_fh.read()
        template_fh.close()
        return pystache.render(template_stream, value)
    

    更新您的配置器设置,可能在__init__.py

    def main(global_config, **settings):
      config = Configurator(settings=settings)
      # ...
      # Use Mustache renderer
      config.add_renderer(name='.mustache',
        factory='myapp.mustacherenderer.MustacheRendererFactory')
      # ...
    

    在您的视图中使用:

    @view_config(route_name='myview', renderer='myapp:templates/notes.mustache')
    def my_view(request):
      # ...
    

    【讨论】:

      【解决方案2】:

      在金字塔中,渲染器视图参数是一个字符串,它不能是一个类。因此,没有办法只说

      @view_config(route_name='someroute', renderer=MyClassBasedView)
      

      最简单的解决方案可能是手动调用渲染器。

      return Response(pystache.render(ViewClass))
      

      如果你真的想使用金字塔渲染器系统,你可以使用“类的虚线路径+扩展”形式的假渲染器字符串。然后渲染器工厂将解析虚线路径以获取类并返回渲染器。

      我必须说我不确定我是否理解您将如何在金字塔中使用基于 pystache 类的视图。使用返回值的方法定义类似乎比返回字典更复杂,并且在这些方法中计算值而不是在金字塔视图中进行计算可能会导致代码更加混乱。不过,继承可能有一些我没有考虑过的优点。


      至于 pystache,文档似乎仅限于 pypi page,但 the code 干净且易于阅读(我在回答问题之前略读了一遍)。

      【讨论】:

      • Mustache 模板在精简控制器和清理模板方面做得很好。在 PHP 中使用 mustache,我学会了喜欢它...
      • 我正在使用基于类的视图...有什么方法可以让基本控制器析构函数完成页面的呈现?还是每个视图都必须返回响应?
      • 类似def home(self): self.view.set(foo=bar) def render(self): return Response(self.view.render()) 并设置某种类型的事件系统来调用渲染
      • 金字塔视图只不过是返回响应的可调用。如果你想要复杂的行为,你总是可以自己实现它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2012-04-05
      • 2019-09-14
      相关资源
      最近更新 更多