Home > OS >  How to use Django json_script in a for loop
How to use Django json_script in a for loop

Time:10-23

Let's say we have in a template a table like

{% for object in object_list %}
   <tr>
      <td id="id-{{object.id}}">{{ object.id }}</td>
   </tr>
{% endfor %}

I'm thinking of using object.id for events, like onclick, to know exactly which object.id was used.

How do you use json_script to get the object.id in a JavaScript script?

CodePudding user response:

In the case of the question we have a table and we want to have a button to copy the object.id to use in JavaScript.

There are various ways to do that and json_script is not one of them.

As noted by Abdul Aziz Barkat

json_script will end up giving you things like 1 and so on and so forth, for (repeated) single attribute data like yours it is unwieldy / overkill, an attribute on your element is much more suitable for your case. Go for json_script in case you have a proper collection (list / dictionary, etc.) that you want to pass to JavaScript.

Instead, we could do something like this in the button

  • onclick="copyId('{{object.id}}')"
  • id="js-copy-id-btn-{{object.id}}"
<table>
  <thead>
    <tr>
      <th>ID</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
      {% for object in object_list %}
      <tr>
          <td>{{object.id}}</td>
          <td><button id="js-copy-id-btn-{{object.id}}" onclick="copyId('{{object.id}}')">Copy ID</button></td>
      </tr>
      {% endfor %}
  </tbody>
</table>

Then the JavaScript could look like

<script>
  function copyId(id) {
    // ...
}
</script>

Another solution for passing data to JavaScript in a Django Template is using the data attributes, as suggested by Adam Johnson

{% for object in object_list %}
   <tr>
      <td data-obj-id={{object.id}} >{{ object.id }}</td>
   </tr>
{% endfor %}


<script>
    const objs = document.querySelectorAll(".obj")
    objs.forEach(obj => {
        let id = obj.dataset.objId
        obj.addEventListener('click', function(event) {
          // Whatever you have to do with the id on click
        })
    })
</script>
  • Related