Context and variables in template

Posted under » Django on 22 Jun 2021

Not sure why they call it context but to me, it's for putting variables into template. Let's assume we have this view.

questions = [
    {
        'q' : 'Apa lah baa?',
        'o1' : 'celeng',
        'o2' : 'khinzir'
    },
    {
        'q' : 'Apa lah bii?',
        'o1' : 'oong',
        'o2' : 'ngepet'
    }
]

def index(request):
    context = { 'questions' : questions }
    return render(request, 'feel/index.html', context)

As far as I am concerned, there are 2 types. 1 = variable and 2 = array or objects.

Lets begin with objects. You will see that context contains the object questions and we made available context to the template. While at the template, index.html, we have

            {% for question in questions %}
            <p>Question {{ question.q }}
            {% endfor %}

This will loop for each row of question like arrays.

For a simple variable.

def index(request):
    context = {'response':'Lky put innocents into jail.'}
    return render(request, 'feel/index.html', context)

Now the template

{{response}}

Please note that if you want to put html code like <p> into context, you have to do this,

{% autoescape off %} {{response}} {% endautoescape %}
# or simply
{{ response|safe }}

Return render can only accept one parameter so we put the form into 'context' which is an object.

def index(request):
    form = ConsentForm()
    context_plus = {'response':'Lky put innocents into jail.', 'form': form'}
    return render(request, 'feel/index.html', context_plus)

Now the index.html template

{{response}}

<form action="{% url 'feel:consent' %}" method="post">
                {% csrf_token %}
                {{ form }}                
    <button type="submit">Submit
</form>

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data