Send objects to a base.html Django template

Asked

Viewed 1,428 times

3

My situation is this, I have a file base.html where more than one page extend in it. My question is, how do I send two objects to this file, so that these objects are shown in all other views, which give the extend on this page (base.html);

  • Your explanation is a bit confusing, how could a page give a more of a "extend" in the template? When you say "da um extend", you’re saying that the control of this template of yours is getting two class inheritances, that’s it?

  • no, like, the base is a masterpage, and the other pages, they extend it {% extends "base.html" %}

2 answers

5


My question is, how do I send two objects to that file

Well, to send two objects to a template you can go through context of function render

Ex:

def foo(request):
    object1 = Object1.object.all()
    object2 = Object2.object.all()

    context = {'object1': object1, 'object2': object2}

    return render(request, 'template.html', context)

so that these objects can be shown in all other views, which extend on that page(base.html)

The variables/objects you send to the template, are only available for the template that was sent.

In order for the variables/objects to be available in the other template it will be necessary to use context Processor.

Ex:

py views.

def foo(request):
    object1 = Object1.object.all()
    object2 = Object2.object.all()

    context = {'object1': object1, 'object2': object2}

    return context

py Settings.

TEMPLATE_CONTEXT_PROCESSORS += ("sua_app.views.foo", )
  • That’s just what I needed. VLW man

4

You can do it this way in your view:

{% extends variavel %}

And in the project something like this:

import django.http
from django.shortcuts import render_to_response
# declarando uma constante aqui
INDEX_EXTEND = "index.html"
# e utilizando algo como isso
def response(request) :
    return render_to_response("base.html", {'variavel': INDEX_EXTEND})
Read more here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#extends

Browser other questions tagged

You are not signed in. Login or sign up in order to post.