简体   繁体   English

如何在 Django 2 模板中生成绝对 url

[英]How to generate absolute urls in Django 2 templates

I have an html template, which is used to render an email, in that template, I want to attach verification links.我有一个 html 模板,用于呈现电子邮件,在该模板中,我想附加验证链接。

I am using the following code to generate the link我正在使用以下代码生成链接

{% url 'verify_email' token=token email=email %}

but this one generates following URL instead of absolute URL.但是这个生成以下 URL 而不是绝对 URL。

在此处输入图片说明

I read this SO thread我读了这个 SO 线程

and some initial google results but all of them seems old and not working for me.和一些最初的谷歌结果,但所有这些结果似乎都很旧,对我不起作用。

TLDR: How do I generate absolute URLs in Django2 template files TLDR:如何在 Django2 模板文件中生成绝对 URL

You can use the build_absolute_uri() referenced in the other thread and register a custom template tag.您可以使用其他线程中引用的build_absolute_uri()并注册自定义模板标记。 Request is supplied in the context (that you enable via takes_context ) as long as you have django.template.context_processors.request included in your templates context processors.只要您的模板上下文处理器中包含django.template.context_processors.request ,就会在上下文中提供请求(您通过takes_context启用)。

from django import template
from django.shortcuts import reverse

register = template.Library()

@register.simple_tag(takes_context=True)
def absolute_url(context, view_name, *args, **kwargs):
    request = context['request']
    return request.build_absolute_uri(reverse(view_name, args=args, kwargs=kwargs))

More on where and how to do that in the docs . 在文档中更多地了解在哪里以及如何做到这一点。

Then you can use the tag in your template like this:然后您可以在模板中使用该标签,如下所示:

{% absolute_url 'verify_email' token=token email=email %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM