How to render a standalone page in a question type, with mustache templates?

How to render a standalone page in a question type, with mustache templates?

by André Storhaug -
Number of replies: 3

Hi!

I am extending some functionality for the shortmath question type. I need to create a new separate page for providing some complex admin settings. This page is to be accessible via a link in the settings page.

The problem is that I want to use Mustache templates (rendered via PHP) for generating the page contents. So, for this to work I need a renderer class (ideally placed under classes/output). But since this plugin is a question type, I already have a specialized renderer extending qtype_renderer.

So, one option is to define the required render_something methods in the existing qtype_shortmath_renderer class. However, since this renderer is mainly meant for rendering questions, I feel like this might be the wrong approach? Alternatively, I could make an additional renderer class, extending plugin_renderer_base. But then calling $PAGE->get_renderer('type_shortmath') won't work properly with two renderers, so I would have to manually instantiate the renderer. However, I'm not sure of all the implications this would make.

So to sum up. What is the recommended way to generate page contents with Mustache templates, for a standalone page in a question type?

Average of ratings: -
In reply to André Storhaug

Re: How to render a standalone page in a question type, with mustache templates?

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
You shouldn't need any renderer code at all to use a mustache template - as long as the class of your object being rendered implements templatable and renderable and there is a template with the same name as this class, you just need to call $OUTPUT->render($myinstance) and it should automatically call $myinstance->export_for_template() and $OUTPUT->render_from_template() for you.

So, to be clear, you should have:
myplugin/classes/example.php:
namespace qtype_myplugin;
class example implements \renderable, \templateable {
   public function export_for_template($output) { ... } 
}

myplugin/templates/example.mustache:
{{! Whatever needs to go in the template}}

Then:
$myinstance = new example();
echo $OUTPUT->render($myinstance);
Average of ratings: Useful (3)
In reply to Davo Smith

Re: How to render a standalone page in a question type, with mustache templates?

by André Storhaug -
Thank you very much! That did it 😁
In reply to André Storhaug

Re: How to render a standalone page in a question type, with mustache templates?

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
Also, you can just add whatever extra methods you like to your question type renderer, in addition to the ones that Moodle core wants.