简体   繁体   English

Pyramid - 是否可以在我的视图可调用中将我的 mako 模板呈现为字符串?

[英]Pyramid - Is it possible to render my mako template as a string within my view callable?

I have a view callable that does looks similar to:我有一个看起来类似于以下内容的可调用视图:

def post_comment(request):
    """ Posts the users comment to the thread """

    try:
        new_comment = comments.post()
    except InvalidComment as e:
        return {'success' : False, 'message' : e.message}

    # need to do something like:
    new_comment = pyramid.template.render(new_comment)

    return {'success' : True, 'message' : new_comment}

The route config for this view callable is:此视图可调用的路由配置是:

config.add_route('post_comment',
                 '/comments/{link_id}/post',
                 view='site.views.post_comment',
                 view_renderer='json')

Using this, I can AJAXify my comment submissions and have a shiny web 2.0 website.使用它,我可以对我的评论提交进行 AJAXify 并拥有一个 shiny web 2.0 网站。 The problem is, I'd like to render new_comment through my mako template to build the HTML and return that.问题是,我想通过我的 mako 模板渲染new_comment来构建 HTML 并返回它。 However, I can't find a way to do this.但是,我找不到这样做的方法。

How can I render a mako template within my view callable to return the HTML as a JSON response?如何在可调用的视图中渲染 mako 模板以将 HTML 作为 JSON 响应返回?

You can call render directly using the documented Pyramid API here: http://docs.pylonsproject.org/projects/pyramid/1.0/api/renderers.html#pyramid.renderers.render您可以使用此处记录的 Pyramid API 直接调用renderhttp://docs.pylonsproject.org/projects/pyramid/1.0/api/renderers.html#pyramid.renderers.render

from pyramid.renderers import render

def my_view(request)
    renderer_dict = {} # dictionary of values to pass to the renderer
    new_comment = render('new_comment.mako', renderer_dict, request)
    …

I'm not sure I understand your question but I think you need 2 views, one for json and another for the mako one.我不确定我是否理解您的问题,但我认为您需要 2 个视图,一个用于 json,另一个用于 mako。 For the mako view follow the official docs and mmerickel's answer.对于 mako 视图,请遵循官方文档和 mmerickel 的回答。 If you want to have multiple view callables within the same class you can have a look to pyramid_handlers .如果您想在同一个 class 中拥有多个视图可调用对象,您可以查看pyramid_handlers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM