使用Traversal时如何生成要查看的URL? [英] How to generate URL to view when using Traversal?

查看:43
本文介绍了使用Traversal时如何生成要查看的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 URL Dispatch 时,我们可以轻松生成视图的 URL,因为每个视图都有不同的 route_name,例如:

When URL Dispatch is used, we can easily generate a URL to a view because every view has a distinct route_name like:

login.py:
@view_config(route_name='login')

index.pt:
<a href="${request.route_url('login')}">Login</a>

但是如何在遍历中做到这一点呢?由于没有可用资源登录"的实例,我不知道如何生成 URL 以查看登录信息.

But how to do this in traversal? Since there is no instance of resources 'Login' available, I don't know how to generate URL to view login.

推荐答案

在遍历中,您需要了解树的结构,并且必须能够按需加载上下文对象.URL 是根据上下文生成的,使用其位置感知属性 __name____parent__ 来构建 URL.

In traversal you are required to know the structure of your tree, and you must be able to load context objects on demand. The URLs are generated with respect to a context, using its location-aware properties __name__ and __parent__ to build the URL.

/
|- login
|- users
   |- 1
      |- edit

假设我们有一个 User(id=1) 上下文对象,我们想登录.如果您的视图是通过 @view_config(context=Root, name='login') 注册的,那么您可以通过 request.resource_url(request.root, 'login')<生成 url/代码>.这是我们告诉 Pyramid 生成一个相对于树根的 URL.

So let's say we have a User(id=1) context object, and we want to login. If your view is registered via @view_config(context=Root, name='login'), then you can generate the url via request.resource_url(request.root, 'login'). This is us telling Pyramid to generate a URL relative to the root of the tree.

另一方面,如果我们在登录状态并且想要让用户进行编辑,您必须为该用户加载一个位置感知User 对象以生成 URL.request.resource_url(user, 'edit') 其中 user 是具有有效 __name__<的 User(id=1) 实例/code> 和 __parent__ 属性.

On the other hand, if we are at login and we want to take the user to edit you must load a location-aware User object for that user in order to generate the URL. request.resource_url(user, 'edit') where user is an instance of User(id=1) with valid __name__ and __parent__ attributes.

如果您传入一个没有位置感知__parent__ 的上下文,则将生成 URL,就像您的用户安装在 / 上一样,因为这是 Pyramid 唯一合理的地方认为该对象会在您的树中.

If you pass in a context without a location-aware __parent__ the URL will be generated as if your user was mounted at / because that's the only sane place for Pyramid to think the object would be in your tree.

加载位置感知对象的能力是我们强调遍历最适合持久对象树的原因,而不是动态生成的对象树.如果您想为其生成 URL,直接加载用户并为其填充 __parent____name__ 会方便得多.

The ability to load a location-aware object is why we stress that traversal works best with a persistent tree of objects, not one that is generated on the fly. It's much more convenient to directly load the user and have its __parent__ and __name__ already populated for you if you want to generate URLs for it.

这篇关于使用Traversal时如何生成要查看的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆