【问题标题】:How to pass a variable to template in Django如何在Django中将变量传递给模板
【发布时间】:2015-08-27 05:36:02
【问题描述】:

我对 django 很陌生,经过几个小时的尝试,没有任何效果。

我有一个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')

我有一个 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 %}

表格完美呈现,但该消息不会显示。

谢谢。

【问题讨论】:

  • 请注意,类名should 通常使用 CapWords 约定。
  • @ErnestTen 我会记住这一点的,谢谢。

标签: python django templates view


【解决方案1】:

你可以add extra context使用get_context_data方法:

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

【讨论】:

  • 这就像一个冠军~~我遇到了 get_context_data 函数但没有尝试,谢谢!
【解决方案2】:

只写下一行或将行移到if循环之外。

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

为什么不可见?

因为模板中写有if 条件。 {% if ssp %}

【讨论】:

  • 显示文本“总点击量是”。但是消息变量没有通过。
  • @viviwill:好的,你能在代码中硬编码消息吗?喜欢(request, 'ssp/sspTableView.html', {'message': "I am message"})
猜你喜欢
  • 2019-04-03
  • 1970-01-01
  • 2014-11-30
  • 2015-08-10
  • 2015-06-22
  • 2011-05-09
  • 1970-01-01
  • 2020-04-24
  • 2020-10-20
相关资源
最近更新 更多