定义“全局变量"在 Django 模板中 [英] Defining "global variable" in Django templates

查看:18
本文介绍了定义“全局变量"在 Django 模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做类似的事情:

{% extends 'base.html' %}
{% url myapp.views.dashboard object as object_url %}
{% block sidebar %}
... {{ object_url }} ...
{% endblock %}
{% block content %}
... {{ object_url }} ...
{% endblock %}

Django 文档说 url templatetag 可以在上下文中定义一个变量,但我在以下块中没有获得 object_url 的任何值.

Django documentation says url templatetag can define a variable in context, but I don't get any value for object_url in the following blocks.

如果我将 url templatetag 放在每个块的开头,它会起作用,但我不想重复自己".

If I put the url templatetag at the beginning of each block, it works, but I don't want to "repeat myself".

有人知道更好的解决方案吗?

Anyone knows a better solution?

推荐答案

如果 URL 是视图特定的,您可以从视图传递 URL.如果 URL 需要在您的模板中真正具有全局性,您可以将其放在 上下文处理器:

If the URL is view specific, you could pass the URL from your view. If the URL needs to be truly global in your templates, you could put it in a context processor:

def object_url(request):
    return {'object_url': reverse('myapp.views.dashboard')}

这篇关于定义“全局变量"在 Django 模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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