Template tag for Javascript code generation

Issue #11 wontfix
Erik Telepovský created an issue

It would be great if the javascript code could be generated through template tag for example. User would define all necessary attributes in his view and they would be set as values for javascript dataTable function.

Comments (3)

  1. Former user Account Deleted

    I agree that it would be nice to have a neatly packaged tag for the js, but I'm wondering if it would ever be generalizable enough to be useful to more than one person. I created a tag myself, but I've already had a couple cases in the project that I created it for where it needed further modification.

    In case you'd like it, here's the code that I used.

    @register.filter
    def make_script(url_name):
        script = """
        <script>
            $(document).ready(function() {
                var dtUrl = \"""" + reverse(url_name) + """\";
                var table = $('#datatable').DataTable( {
                    "processing": true,
                    "serverSide": true,
                    "ajax": dtUrl,
                    "lengthMenu": [[20, 50, 100, -1], [20, 50, 100, "All"]]
                } );
                $('#button-id-apply-filters').click(function() {
                    var params = $('#datatable-filter').serialize();
                    table.ajax.url(dtUrl + "?" + params).load();
                });
            } );
        </script>
        """
        return mark_safe(script)
    

    You have to supply a reverse URL name for the tag to point to the AJAX data, and then insert the filter in your html template using something like {{ data_url_name|make_script }}. You'll need to name your table "dataTable" in the template, or change it in here to something else.

    The second part of the JS watches a button attached to a group of filters that are in turn passed to the AJAX. When the filters get updated, the AJAX refreshes with the new parameters.

  2. Erik Telepovský reporter

    Yes, something like this, but more generic using like this:

    {{ my_datatable_obj|make_script }}
    

    The script would take more data from the datatable object, not just the URL. This way you could configure the lengthMenu for example and much more...

  3. Log in to comment