-1

I have a variable in the file views.py of my app directory. I need to print that variable inside my template. How can I do That?

kashish
  • 159
  • 4
  • 12

1 Answers1

0

You can pass the variable into context dictionary and render it in the template,

When you use a Django Template, it is compiled once (and only once) and stored for future use, as an optimization. A template can have variable names in double curly braces, such as {{ myvar1 }}, {{ myvar2 }}.

A Context is a dictionary with variable names as the "key" and their values as the "value". Hence if your context for the above template looks like: {myvar1: 101, myvar2: 102}, when you pass this context to the template render method, {{ myvar1 }} would be replaced with 101 and {{ myvar2 }} with 102 in your template. This is a simplistic example, but really a Context object is the "Context" in which the template is being rendered.

As for a ContextProcessor, that is a slightly advanced concept. You can have in your settings.py file listed a few Context Processors which take in an HttpRequest object and return a dictionary (similar to the Context object above). The dictionary (context) returned by the Context Processor is merged into the context passed in by you (the user) by Django.

A use case for a Context Processor is when you always want to insert certain variables inside your template (for example the location of the user could be a candidate). Instead of writing code to insert it in each view, you could simply write a context processor for it and add it to the TEMPLATE_CONTEXT_PROCESSORS settings in settings.py.

An example,

In your views.py

foo = 'bar'
context = {'foo': foo }
return render(request, 'template_name', context)

And in your template, you can access the variable,

{{ foo }}
zaidfazil
  • 9,017
  • 2
  • 24
  • 47