gpt4 book ai didi

python - 在 Django 中不属于您网站的抽象网址

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:28 25 4
gpt4 key购买 nike

例如,在您的 django 站点上,您有许多按钮/链接可以将某人重定向到 http://stackoverflow.com .

不必每次都硬编码

<a href="http://stackoverflow.com" target="_blank" rel="noopener">

有没有一种方法可以将它抽象化,这样您就可以拥有一大堆 url,并且您可以在带有 django 标签的模板中引用 with?

stackoverflow = "http://stackoverflow.com"
<a href="{{ stackoverflow }}" target="_blank" rel="noopener">

最佳答案

当你在 View 中写类似的东西时

return render(request, 'polls/index.html', context)

context 是一个字典,您可以在其中存储所需的值,然后通过 {{ your_key }} 在模板中引用它们。

您还可以有一个模块,您可以在其中定义/添加它们分组在一个 sites 字典中,然后将其导入 View 并做

from external_urls import sites
...
context.update(sites)
return render(request, 'polls/index.html', context)

注意站点名称与其他上下文键的冲突。也许可以代替

...
context['sites'] = sites

并在模板中使用

   {{ sites['sitename'] }}

您还可以考虑通过设置加载此站点

关于python - 在 Django 中不属于您网站的抽象网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56623356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com