如何让 Django TemplateLoader 查看当前上下文或请求?

发布于 2024-09-01 20:33:12 字数 141 浏览 2 评论 0原文

我正在尝试构建一个 Django TemplateLoader,但我无法让它“查看”当前的上下文或请求,因此我无法用它做太多事情。

有谁知道我如何让 Django TemplateLoader 做到这一点?

非常感谢

I' m trying to build a Django TemplateLoader, but I can't make it 'see' either the current Context or Request, so I can't really do much with it.

Does anyone know how I can make a Django TemplateLoader do this?

Many Thanks

Joe

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

<逆流佳人身旁 2024-09-08 20:33:12

做出有关模板的决定的地方在您的视野中。在那里,您可以访问请求,并且可以根据您喜欢的条件动态构造模板名称。例如,

def my_view(request, ...):
  ...
  template_name = 'template.html'
  if is_mobile(request): template_name = 'mobile_' + template_name
  template = get_template(template_name)
  context = RequestContext(request, {...})
  return HttpResponse(template.render(context))

您提供 is_mobile() 的位置。更好的方法是提供一种方法,该方法接受请求和模板名称,并返回经过适当修改的方法(以便您可以对该逻辑进行一次编码,而不是分散在多个视图中)。

您还可以从 select_template( ),它获取候选模板名称列表,返回找到的第一个模板。

The place to make decisions about templates is in your view. There, you have access to the request, and can dynamically construct a template name depending on whatever conditions you like. E.g.,

def my_view(request, ...):
  ...
  template_name = 'template.html'
  if is_mobile(request): template_name = 'mobile_' + template_name
  template = get_template(template_name)
  context = RequestContext(request, {...})
  return HttpResponse(template.render(context))

Where you provide the is_mobile(). Better would be to provide a method that takes a request and template name, and returns one appropriately modified (so that you can encode that logic once, rather than scattering across several views).

You might also get some leverage from select_template(), which takes a list of candidate template names, returning a template for the first one it finds.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文