简体   繁体   中英

How to pass a variable to template in Django

I'm pretty new to django and after a few hours of trying, nothing works.

I have a views.py:

class sspView(generic.ListView):
    template_name = 'ssp/sspTableView.html'
    context_object_name = 'ssp'
    message = "yo, this is the message"

    def message(request):
        return render(request, 'ssp/sspTableView.html', {'message': message})

    def get_queryset(self):
        return googleData.objects.order_by('date')

I have a template.html:

{% if ssp %}
<p>total click is: {{ message }}</p>
<table>
    {% for googleData in ssp %}
    <tr>
        <td>{{ googleData.date }}</td>
        <td>{{ googleData.account }}</td>
    </tr>
    {% endfor %}
</table>
{% endif %}

Table renders perfectly, but that message just won't show.

Thank you.

Write only following line or move line outside of if loop.

<p>total click is: {{ message }}</p>

Why not visible?

because there is if condition written in template. {% if ssp %}

You can add extra context using get_context_data method:

def get_context_data(self, **kwargs):
    context = super(sspView, self).get_context_data(**kwargs)
    context['message'] = 'Hello, context!'
    return context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM