0

I'm working on a Django project in which I used render_to_string to pre-render HTML templates from the backend, and then I send them to the frontend as a response to an ajax call.

        rendered_html.append(
            [render_to_string("webapp/popup.html", context=shop_context), location['Logo'], location['LONG'],
             location['LAT'], location['id']])

    return JsonResponse({"rendered_html": rendered_html})

I am appending this rendered_html into the frontend with javascript. The HTML code and the Django context variable work fine but the javascript in the file does not work at all. If I see the elements section from the developer's console, I can see that javascript is included but it does not work, not even a small console.log works.

Is there a workaround to this or am I doing something wrong? Any help will be appreciated.

ahsan mukhtar
  • 93
  • 1
  • 7
  • Does this answer your question? [Dynamically load JS inside JS](https://stackoverflow.com/questions/14521108/dynamically-load-js-inside-js) – Abdul Aziz Barkat Apr 14 '21 at 07:23
  • @AbdulAzizBarkat no it does not. This is a solution to import Js in existing js. I need to pre-render html file in the backend and the javascript does not render. – ahsan mukhtar Apr 14 '21 at 08:23
  • You say: "_I can see that javascript is included but it does not work_" surely that means the javascript **is** rendered. That question has plenty of answers with similar use case to yours. Furthermore your question is not _reproducible_ you have not given enough information to reproduce your problem, please see how to write a [mre]. – Abdul Aziz Barkat Apr 14 '21 at 08:27

1 Answers1

0

Faced the same problem. To solve the described problem, I put the js code in a separate js file, in the html I indicated the path to it in the script tag. Then when I get the line of code returned by (render_to_string in view) I search for the script tags using a regular expression and load the files they have written in src

Template

1 way:

$.ajax({
    type: "GET",
    url: '/get_html/',
    data: {
       
    },
    success: function(data) {
        const content = document.querySelector('.main__content.inner');
        content.innerHTML = data['html'];
           
        const scripts = data['html'].match(/<script (.*?)<\/script>/g)
        
        scripts.map((script) => { 
            script = script.replace('"><\/script>', '').replace('<script src="/', '');
                console.log(script)
                loadJS(script);
            })
        },
    });


function loadJS(file) {
    const content = document.querySelector('.main__content.inner');
    const jsElm = document.createElement("script");
    jsElm.src = file;
    content.appendChild(jsElm);
}

2 way:

$.ajax({
    type: "GET",
    url: '/get_html/',
    data: {
        },
    success: function(data) {
        $(".main__content.inner").html(data['html']);
            
       },
    failure: function(data) { 
        console.log('Get html error');
       }
    });

View

class GetHtmlView(View):
    def get(self, request):
        if request.is_ajax():
            html = render_to_string('your html path')
            return JsonResponse({'html': html})

If you have any additional questions, I will be glad to answer. I also wanted to see if you found another way to solve this problem.

Khava
  • 56
  • 1
  • 4