python - Pyramid/Pylons Framework - 关于我如何使用 'helpers' 完成某些任务的意见

标签 python pylons helper pyramid

在 Pyramid 中,我创建了一个类似于 pylons 中的“助手”功能。

我的 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 的任何内容都可以在整个应用程序中使用,而您可以仅在您希望它位于的 View 中返回 createBlog 函数。一个鲜为人知的花絮是如果您使用基于类的 View ,则实际的类实例在 View 中可作为 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()} 调用渲染博客。

关于python - Pyramid/Pylons Framework - 关于我如何使用 'helpers' 完成某些任务的意见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379668/

相关文章:

ruby-on-rails - 从 Rails 中的 Controller 调用辅助方法时出现 "undefined method"

python - Django:如何创建到 View 的通用 url 路由?

c# - 如何制作支持泛型类型的 HTML Helpers?

sql - 右外连接没有得到相同的结果不知道为什么 (=*)

python - sqlalchemy with_hint 不工作

python - SQLAlchemy 核心插入使( Pyramid )作用域 session 挂起

python - 获取 fixture 中的主键(id)(Python,SQLAlchemy)

python - 从 python 运行 linux 命令

python - Python线程启动开始时间

python - 将具有字节字符的字符串对象转换为字节对象?