Django Template integration with JavaScript




Django template with Javascript integration helps in solving many functional requirements. I have explained on such requirement for the sake of understanding the integration.

Its a very frequent requirement that text displayed on the web page (especially in table cell) should be limited to say 100 characters and the more option should display the remaining text.This requirment can be met using Django tempate + Javascript integration.

 

Sample Code:

Django Template : Index.html

I am using a simple django model (ztest)  with 1 comment field and data is being passed from my Django view to template.The output is diplayed in a table. During the intial output i am restricting the length of the string to 150 characters.

A href tag is added to call the javascript function when the more button is clicked by the user and Cell element id is set to ztest.id key. 

When more Href key is clicked by the user, the complete comment and id is passed as a variable to Javascript function and the inner HTML of <td> element is modified to show complete text.

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script>
    function showmore(zid,zcomment) {
            alert(zcomment);
            document.getElementById(zid).innerHTML = zcomment ;

    }
</script>


  </head>
  <body>
<table class="table table-borderless">
  <tbody>
	<tr>
	  <td id={{ztest.id}} style="width: 10%;">
            {{ ztest.comments|truncatechars:150 }} <a href="javascript:showmore({{ztest.id}},'{{ztest.comments}}')" >more</a>
        </td>
	</tr>
	<tr>
	  
	</tr>
  </tbody>
</table>

 </body>
</html>

 

Output

 

 

 

Note :

While passing variables to JS function , integer can be passed directly , but the string variable should be passed using ' '




Reference

Pass variables to JavaScript Function

https://www.javascripttutorial.net/javascript-pass-by-value/

Hide visibility of table tags

https://stackoverflow.com/questions/916528/how-can-i-hide-a-td-tag-using-inline-javascript-or-css

Django template Truncate

https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#truncatechars




Private

This area is only for registered user. Please register.