繁体   English   中英

将Django模板变量传递给js数据表

[英]Passing django template variables to js datatables

嗨,我想使用JS数据表库创建表。

将模板中的值传递给js脚本时遇到问题。 我从要显示的表中创建了JSON对象。 它正确传递给模板,当我显示它时,一切都很好,但是当尝试将其传递给脚本时,什么也没发生,所以我得到了空表。

我就是这样的:

class VotesList(generic.ListView):
    model = Vote
    template_name = 'votes-list.html'
    def get_context_data(self, **kwargs):
        votes = Vote.objects.all().values('user', 'group', 'council')
        votes_json = json.dumps(list(votes))
        context = super(VotesList, self).get_context_data(**kwargs)
        context['orderby'] = self.request.GET.get('orderby', 'created_date')
        context['json_data'] = votes_json

    return context

模板:

{% block javascript %}
{% load static %}

<script type="text/javascript">
$(document).ready(function() {

    var json=JSON.parse('{{ json_data | safe }}');
    $('#votes_list').DataTable({
       data: json,
        columns:[
        { title: "user" },
        { title: "group" },
        { title: "council" }]
    } );
};

</script>

{% endblock %}

{% block content %}

    <p>{{ json_data | safe }}</p> <<< here data is printed fine
    {% if vote_list %}

        <table id="votes_list" class="display", style="width:100%">
            <thead>
                <tr>
                    <th>Właściciel</th> 
                    <th>Grupa</th> 
                    <th>Rada</th> 
                </tr>
            </thead>

        </table>

    {% else %}
        <p>Brak głosowań!</p>
    {% endif %}

{% endblock %}

输出数据如下所示:

[{"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": 1}, {"user": 3, "group": 1, "council": 1}, {"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": 2}, {"user": 1, "group": 1, "council": 2}, {"user": 3, "group": 1, "council": 1}, {"user": 2, "group": 1, "council": 1}, {"user": 1, "group": 1, "council": 2}, {"user": 1, "group": 2, "council": 1}, {"user": 1, "group": 1, "council": 1}, {"user": 1, "group": 1, "council": 1}]

我的第二个问题是关于其他问题:我存储大量信息作为选择:

STATUS_INACTIVE = 0
STATUS_ACTIVE = 1
STATUS_FINISHED = 2
STATUS_CHOICES = (
    (STATUS_INACTIVE, 'Inactive'),
    (STATUS_ACTIVE, 'Active'),
    (STATUS_FINISHED, 'Finished'),
)

如何将数字而不是此人类可读的值(“无效”)传递给上述JSON?

如果您在这样的视图中传递数据

class VotesList(generic.ListView):
    model = Vote
    template_name = 'votes-list.html'

    def get_context_data(self, **kwargs):
        context = super(VotesList, self).get_context_data(**kwargs)
        context['votes'] = Vote.objects.all()
        return context

然后,您可以在模板中


 {% block javascript %} {% load static %} <script type="text/javascript"> $(document).ready(function() { $('#votes_list').DataTable({ }); }); </script> {% endblock %} {% block content %} {% if vote_list %} <table id="votes_list" class="display", style="width:100%"> <thead> <th>Właściciel</th> <th>Grupa</th> <th>Rada</th> </thead> <tbody> {% for vote in votes %} <tr> <td>{{ vote.user }}</td> <td>{{ vote.group}}</td> <td>{{ vote.countcil }}</td> <tr> {% endfor %} </tbody> </table> {% else %} <p>Brak głosowań!</p> {% endif %} {% endblock %} 

它应该呈现为JS Datatable

对于第一个问题,我会将您的模板变量存储在javascript变量(如var data = "{{ template_var }}" ,然后在要立即使用的地方使用该新变量。 然后,您应该能够处理您要尝试执行的操作。

请注意,其他答案将告诉您仅创建一个表,但是我知道您正在使用DataTables,此外,如果尝试将50个以上的对象加载到表中,则可能会遇到加载速度问题。 因此,做您正在做的事情可能会很好,这将使您能够AJAX并检索具有分页功能的下一组数据。 这是将来可以验证应用程序时可以解决的问题。

对于第一个问题,请尝试在</thead>标记后添加<tbody></tbody> 重新运行代码。

为了使DataTables能够增强HTML表,该表必须是有效的,格式正确的HTML,并且具有标头(thead)和单个正文(tbody)

还有另一种更简单的方法来呈现数据表。

views.py-

context['json_data'] = votes # no need to use json.dumps


在html-

   <table id="votes_list" class="display", style="width:100%">
        <thead>
            <tr>
                <th>Właściciel</th> 
                <th>Grupa</th> 
                <th>Rada</th> 
            </tr>
        </thead>
        <tbody>
            {% for data in json_data %}
                <tr>{{ data.user }}</tr>
                <tr>{{ data.group }} </tr>
                <tr>{{ data.council }} </tr>
            {% endfor %}
        </tbody>
   </table>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#votes_list').DataTable();
        }
    </script>

对于第二个问题-

{% if data.user == 1 %}
   Active
{% elif data.user == 2%}
   Inactive
{% else %}
   Finished
{% endif %}
OR 
{% if data.group == 1 %}
   {{ status_dict.0 }}
{% elif data.group == 2%}
   {{ status_dict.1 }}
{% else %}
   {{ status_dict.2 }}
{% endif %}

>>>status_dict = dict(STATUS_CHOICES)
{0: 'Inactive', 1: 'Active', 2: 'Finished'}

在数据表中-您可以应用相同的逻辑。 例如-

  "columns": [
    { "data": "engine" },
    { "data": "browser" },
    {
      "data": "platform",
      "render": function(data, type, row, meta) { 
                      if(true)
                          return “display this” 
                      };
                      return “false"
    }
  ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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