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 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">
    <!-- 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="" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    function showmore(zid,zcomment) {
            document.getElementById(zid).innerHTML = zcomment ;


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







Note :

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


Pass variables to JavaScript Function

Hide visibility of table tags

Django template Truncate


This area is only for registered user. Please register.