django - 如何将变量传递到 django 中包含的模板中

标签 django django-templates

我是 Django 新手,无法实现一些微不足道的事情。请帮我解决这个问题。

  1. 我在views.py中设置变量pgurl
  2. 能够访问我的 with_tag.html 模板中的变量 {{pgurl}}。该模板本身包含一个 pagination.html 模板
  3. 在 pagination.html 中,我无法使用变量 {{pgurl}} 并且没有打印任何内容

如何将此变量传递到包含的模板中?

views.py

def with_tag(request, tag, template_name='main/with_tag.html', current_page=1, pgurl=''):
    if request.method == 'GET':
        query_tag = Tag.objects.get(name=tag)
        primes = TaggedItem.objects.get_by_model(Prime, query_tag)
        primes = primes.order_by('-date')
        request.page = current_page
        tcm_pp = TCM_ITEMS_PER_PAGE
        pgurl = request.path
    else:
        return HttpResponseRedirect(request.path)

    return direct_to_template(request, template_name, { 'primes' : primes, 'prime_total' : Prime.objects.count(), 'now': datetime.now(), 'page' : current_page, 'tcm_pp' : tcm_pp, 'tag' : tag, 'pgurl' : pgurl })

with_tag.html

{% extends "base.html" %}
{% load comments %}
{% load pagination_tags %}

...

  {% include "pagination.html" %}
  {% paginate %}

分页.html

{% if is_paginated %}
{% load i18n %}

<div class="pagination">
    {% if page_obj.has_previous %}
        <a href="{{ pgurl }}{{ page_obj.previous_page_number }}{{ getvars }}" class="prev">&lsaquo;&lsaquo; {% trans "previous" %}</a>
    {% else %}
        <span class="disabled prev">&lsaquo;&lsaquo; {% trans "previous" %}</span>
    {% endif %}
    {% for page in pages %}
        {% if page %}
            {% ifequal page page_obj.number %}
                <span class="current page">{{ page }}</span>
            {% else %}
                <a href="{{ pgurl }}{{ page }}{{ getvars }}" class="page">{{ page }}</a>
            {% endifequal %}
        {% else %}
            ...
        {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
        <a href="{{ pgurl }}{{ page_obj.next_page_number }}{{ getvars }}" class="next">{% trans "next" %} &rsaquo;&rsaquo;</a>
    {% else %}
        <span class="disabled next">{% trans "next" %} &rsaquo;&rsaquo;</span>
    {% endif %}
</div>
{% endif %}

最佳答案

如果您发布渲染页面的输出,将会很有帮助。上下文应该被传递,可能是你的模板标签。尝试断言并检查变量是否正确传递。

关于django - 如何将变量传递到 django 中包含的模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1746962/

相关文章:

python - Heroku 上的 Django 不允许我创建 super 用户

python - 用户身份验证模板标签不起作用-Django

django - Django 平面页面的 View ?

Django:有没有更好的方法来加粗当前页面链接

python - 使用migrate命令创建数据库表时出错

django 模板抛出 NoReverseMatch 错误

django - 如何将链接放入 Django 错误消息中

python - render_to_string 似乎删除了变量的值

javascript - 如何根据文本变量选择 MultipleChoice 选项

django-parler 不在管理员中显示标签