How to integrate pystache with pyramid?

2020-07-21 00:27发布

问题:

I would like to use the class based views that pystache offers in my pyramid application, but I'm not entirely sure how to integrate the two properly. I've read this already, but it doesn't talk about using the class based views.

How would I create a new renderer for pystache if I wanted to use class based views? Can somebody help me out here?

Also, while I already know how mustache works, I can't seem to find much information on the python implementation (pystache). Can somebody point me in the right direction here?

回答1:

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):
  # ...


回答2:

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).