Skip to main content
 首页 » 编程设计

python之Pyramid之是否可以在我的可调用 View 中将我的 mako 模板呈现为字符串

2025年05月04日20傻小

我有一个可调用的 View 看起来类似于:

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} 

此 View 可调用的路由配置是:

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

使用它,我可以对我提交的评论进行 AJAX 化,并拥有一个 Shiny 的 Web 2.0 网站。问题是,我想通过我的 mako 模板呈现 new_comment 以构建 HTML 并返回它。但是,我找不到执行此操作的方法。

我如何在我的 View 中呈现一个 mako 模板可调用以将 HTML 作为 JSON 响应返回?

请您参考如下方法:

您可以在此处使用记录的 Pyramid API 直接调用 render:http://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) 
    …