Load rendered mustache template with JS via ajax -> Javascript isn't included anymore.

Load rendered mustache template with JS via ajax -> Javascript isn't included anymore.

by Georg Six -
Number of replies: 3

In our project, we use a webservice via Ajax which returns content which was rendered from a mustache template by the output renderer (extended plugin_renderer_base).

The problem is: The mustache templated includes javascript via the normal js tags. But when the result from the renderer is passed back via Ajax, this javascript inclusion is lost.

Is there a Moodle way to render for Ajax and pass back supplementary javascript after the page is loaded? Or how would you achieve this?

Average of ratings: -
In reply to Georg Six

Re: Load rendered mustache template with JS via ajax -> Javascript isn't included anymore.

by Andreas Grabs -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers Picture of Translators

Hi Georg,

one way is to use the template module from moodle. With this you get a rendered template and the javascript in a way you can run it.
See the documentation here: https://docs.moodle.org/dev/Templates#Rendering_in_JavaScript

Best regards
Andreas

In reply to Andreas Grabs

Re: Load rendered mustache template with JS via ajax -> Javascript isn't included anymore.

by Georg Six -
Hi Andreas,
Thank you for your answer. I considered this already, but this won't work well in our case.

But I want to share my solution:
Actually, I included the javascript call like this in my mustache template:

onclick="require(['local_wunderbyte_table/init'], (init) => {init.init('{{idstring}}', '{{encodedtable}}')}); return false;"

I also trigger the click event automatically after I put the code at the right place on my site. I know, it's hackish but there are some restraints in my project which make it seem the best way.
In reply to Georg Six

Re: Load rendered mustache template with JS via ajax -> Javascript isn't included anymore.

by Andreas Grabs -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers Picture of Translators

Hi Georg,

did you read the chapter after the chapter my link was pointing to?
https://docs.moodle.org/dev/Templates#Template_requires_JavaScript
There is a description how to execute the js after rendering the template.

templates.runTemplateJS(javascript);

This requires the js in the {{#js}}...{{/js}} section of the template.

Best regards
Andreas