Sam Sam - 1 year ago 74
Javascript Question

Using a Javascript search algorithm on a Django context variable

What I'm trying to do is offer search functionality on a webpage where all data is displayed when loading the page. The dataset is not very large (think <500 items) so it would be very user-friendly to offer some search functionality that does not require a page refresh (or any requests for that matter). I've looked at some interesting Javascript libraries (summed up in this answer), and especially Fuse.js and Lunr.js look very suitable for my scenario.

The problem is that I don't know how to apply these libraries -- which seem to search through JSON exclusively -- to the context passed by Django. I have only scratched the surface of the functionality of Django, because I've only started working on it a few days ago, so pardon me if I'm missing something obvious. Thank you!

Answer Source

You just need to output the JSON in your template. You can either pass it directly from your view via json.dumps(), or manually iterate through the data in your template to create the JSON. The first would be preferable.

So, using the Fuse example, your view would do:

def my_view(request):
    data = ... get data from wherever ...
    return render(request, 'template.html', {"data": json.dumps(data)})

and the template:

<script type="text/javascript">
    var data = {{ json_data }}
    var options = ...
    var f = new Fuse(data, options)