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.
Please consider using templates as an alternative to the HTML writer.
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
html_writer::react_component(
string $modulename,
array|string|\stdClass|\JsonSerializable $props,
);
Render a placeholder <div> for a React component mount point.
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-componentwith the module name, including the full@moodle/lms/prefix;data-react-propscontaining JSON-encoded props.
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="{"filter":"latest","limit":25}"></div>
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);