How to integrate pystache with pyramid?

筅森魡賤 提交于 2019-12-04 12:08:59

Implement a 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)

Update your configurator setup, probably in __init__.py:

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

Use in your views:

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

In pyramid, the renderer view argument is a string, it can't be a class. Thus, there is no way to just say

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

The easiest solution might be to call the renderer manually.

return Response(pystache.render(ViewClass))

If you really want to use the pyramid renderer system, you can use a fake renderer string of the form "dotted path to class + extension". The renderer factory would then resolve the dotted path to get the class and return the renderer.

I must say I'm not sure I understand how you would use pystache class based views in pyramid. Defining class with methods that return values seems more complicated than returning a dict, and computing the values in those methods instead of doing it in the pyramid views might lead to more cluttered code. The inheritance might have some advantages I haven't considered, though.


As for pystache, the documentation seems limited to the pypi page, but the code is clean and easy to read (I skimmed through it before answering the question).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!