在pyramid中,我创建了一个类似于pylons中的“helpers”功能。
my helpers.py文件中的一个特殊函数如下:

from pyramid.renderers import render_to_response

def createBlog():
    ## lots of code here ##
    return render_to_response('blog.mako', {'xyz':xyz})

然后在我的其他应用程序中,我可以导入帮助程序并在模板中执行以下操作:
${h.createBlog()}

在我的页面上创建博客。但我只是想知道,这是一种使用帮助程序创建“模块”样式插件的好方法吗?我可以在项目的任何地方轻松使用这些插件。或者这项技术有什么我还没有真正想到的缺陷吗?
谢谢!

最佳答案

这真的取决于你想在全球曝光多少东西。显然,您放入h中的任何内容在整个应用程序中都是可用的,而您可以只在希望它位于的视图中返回createBlog函数。一个鲜为人知的小道消息是,如果使用基于类的视图,那么实际的类实例在视图中可用作view全局变量。例如:

class Foo(object):
    def __init__(self, request):
        self.request = request

    def createBlog(self):
        return render('blog.mako'. {})

    @view_config(...)
    def myview(self):
        return {}

现在在模板中,您可以使用${view.createBlog()}调用render your blog。

10-04 21:28