Skip to main content
Version: main (5.3)

HTML Writer API

Moodle has a class called HTML writer which allows you to output basic HTML tags. This is typically used within renderer functions, for example question/type/*pluginname*/renderer.php.

tip

Please consider using templates as an alternative to the HTML writer.

note

There is no documentation for most of this class. Please read HTML Writer Class Reference for further information.

Methods​

div​

html_writer::div(content, class="", attributes="");

Example usage:

html_writer::div('anonymous'); // <div>anonymous</div>
html_writer::div('kermit', 'frog'); // <div class="frog">kermit</div>

Attributes can be set by an array with key-value pairs.

html_writer::div('Mr', 'toad', array('id' => 'tophat'));
// <div class="toad" id="tophat">Mr/div>

span​

html_writer::start_span('zombie') . 'BRAINS' . html_writer::end_span();
// <span class="zombie">BRAINS</span>

react_component​

Since 5.3
html_writer::react_component(
string $modulename,
array|string|\stdClass|\JsonSerializable $props,
);

Render a placeholder <div> for a React component mount point.

Properties

The $modulename must include the @moodle/lms/ prefix in the module name.

The $props takes the data and JSON-encodes it. You should not pass a JSON-encoded value.

The method outputs the <div> with two data attributes:

  • data-react-component with the module name, including the full @moodle/lms/ prefix;
  • data-react-props containing JSON-encoded props.
A note on React properties

For React components we strongly encourage you to limit the properties to only the initial configuration and preferences.

React properties should not contain additional data.

Historically it was often necessary to include a range of additional properties when writing Mustache template context properties because of limitations in the way that Mustache works. For example it was often necessary to provide certain strings, as well as some hard-to-fetch data. These limitations are not present in React.

Example usage:

echo html_writer::react_component(
'@moodle/lms/core/example',
(object) [
'filter' => get_user_preference('tool_demo/widget_filter', 'all'),
'limit' => get_user_preference('tool_demo/widget_result_limit', 25),
],
);
// <div data-react-component="@moodle/lms/core/example" data-react-props="{&quot;filter&quot;:&quot;latest&quot;,&quot;limit&quot;:25}"></div>
note

If you are rendering a \core\output\react_component_renderable via renderer_base::render(), Moodle calls this method for you.

Generic tags​

html_writer::tag(tag_name, contents, attributes=null);
html_writer::start_tag(tag_name, attributes=null;);
html_writer::end_tag(tag_name);
html_writer::empty_tag(tag_name, attributes=null);
html_writer::nonempty_tag(tag_name, content, attributes=null);
html_writer::attribute(name, value);
html_writer::attributes(attributes_array);