Django: How to convey a context?

I know about passing context to templates, but I'm a little confused in this scenario, please help

class X:

id: name: status: 

Main Class:

 number1: object of X number2: object of X message: "Hello World!" 

I get an Object of Main that has two X objects, but with different contexts. I want to write one template for X and pass it another conetext for ease of use of code and ease of maintenance.

so I'm trying to do this in my view logic, where I have a Main object

 <div class="ui-tabs-panel" id="tab-results"> {% include "render/objectX.html" %} </div> 

and objectX.html :

 {% block content %} <div id="d"> <table id="c"> <tbody> <tr> <td>id : {{ x.id }}</td> <td>name : {{ x.name }}</td> </tr> </tbody> </table> </div> {% endblock %} 

How can I pass Main.number1 (object X) explicitly to the template?

thanks

+4
source share
2 answers

One easy way is to wrap include with the template tag {% with %} . For example, if you have main in your context:

 <div class="ui-tabs-panel" id="tab-results"> {% with main.number1 as x %} {% include "render/objectX.html" %} {% endwith %} </div> 

This will put the number1 object in the context as a variable named x that can be used in the included template.

+5
source

or you can use it as follows

 {% include "render/objectX.html" with x=main.number1 %} 

according to django documention https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#include

+1
source

Source: https://habr.com/ru/post/1316341/


All Articles