Coding Reports
This guide is for whoever writes the code of a report: the structure of the .ht file, the onInit script, the Handlebars template, helpers and partials. It describes the language, not the tools.
- What a report is and how its parts fit together: Report Concepts.
- The window where you write and test it: Report Editor.
- How users choose and print a report: Printing and exporting.
File structure
Section titled “File structure”{ "editor_type": "report_v2", "label": "Equipment record", "description": "Data sheet of a piece of equipment.", "target": ["equipment"], "country": [], "lang": ["en-GB"], "tags": [], "output_type": "html", "template": "<html>...<h1>{{equipment.name}}</h1>...</html>", "script": "async function onInit() { ... }", "helpers": "var helpers = {}", "partials": {}}| Key | Type | Description |
|---|---|---|
editor_type | string | Always "report_v2". |
label | string | Required. Name of the report. |
description | string | Optional description. |
target | string[] | Launch points of the report (see Launch points). |
country | string[] | ISO 3166-1 alpha-2 codes (IT, GB…). |
lang | string[] | App locales (it-IT, en-GB, es-ES, de-DE, fr-FR). |
tags | string[] | Free classification, for example a family such as iso-45001. The format rules are in Report Editor. |
output_type | string | html (default), csv or text. See Printing and exporting. |
template | string | HTML + Handlebars. Its context is the object returned by onInit(). |
script | string | JavaScript defining async function onInit(), which loads the data. |
helpers | string | JavaScript defining var helpers = { ... }: report-specific Handlebars helpers. |
partials | object | Other files included in the template (see Partials). |
Loading data: onInit
Section titled “Loading data: onInit”The report loads its own data. script defines an async function onInit(); whatever it returns becomes the
context of the template: if it returns { equipment, office }, the template uses {{equipment.name}}.
Inside onInit, this gives you:
-
this.runtime.context: where the report was launched from,{}when there is no entityKey Content entity_idid of the entity the report is printed from entity_typeits type, uppercase ( EQUIPMENT,OFFICE,CERTIFICATE…)office_id,office_countrythe office of the entity (or the entity itself, if it is an office) project_id,project_countrythe project unit_id,unit_countrythe unit / supplier, if any -
this.runtime.target: the launch point (e.g.office.equipment_list),nullwhen unknown -
this.fetchAll(url, options): calls a paginated v2indexendpoint and returns all the rows
Data comes from the REST API v2, called with the session of the logged-in user.
Use relative URLs (no leading /):
- one record:
fetch('v2/<resource>/view?id=' + id)(theview/<id>form does not exist) - a list:
this.fetchAll('v2/<resource>/index', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filter: { office_id: id } }) })
async function onInit() { const entityId = this.runtime.context.entity_id; const officeId = this.runtime.context.office_id; const result = { equipment: {}, office: {} }; if (!entityId) { return result; }
const equipmentResponse = await fetch('v2/equipment/view?id=' + entityId); if (equipmentResponse.ok) { result.equipment = await equipmentResponse.json(); }
if (officeId) { const officeResponse = await fetch('v2/office/view?id=' + officeId); if (officeResponse.ok) { result.office = await officeResponse.json(); } }
return result;}How onInit is executed
Section titled “How onInit is executed”- Name and form. The script must define a function named
onInit, normallyasync. If there is no such function, the script does nothing and the template renders with no data.onInittakes no arguments: everything it needs comes fromthis. - Strict mode, private declarations. The script runs in strict mode. What it declares (constants, functions) is
visible only to the script itself: it does not leak into the page and the template or the helpers cannot see it.
You can declare other functions and constants next to
onInit, or inside it, and use them from it. The globals of the page (window,fetch,URL…) are available. thisis only available directly inonInit. It exposes exactly two things:runtimeandfetchAll. A function declared next toonInitdoes not receive it: passthis.runtimeor the values you need as arguments. Arrow functions written insideonInitkeepthisas usual.- The return value is the template context. If
onInitreturns an object, its keys are merged into the data of the template. Return a plain object:undefinedand other non-object values are ignored, and an array would be merged key by key (0,1…), which is never what you want. - Reserved key
partials. The data object holds the partials under the keypartials. Do not return a key with that name fromonInit. - Partials do not run scripts. If a partial is a
.htfile, only itstemplateis used: its ownscriptis not executed. The data of a partial must be returned by theonInitof the report that includes it.
Fetching data
Section titled “Fetching data”fetch is the browser fetch, with the session of the logged-in user: the report sees exactly what the user can
see. Keep in mind:
fetchdoes not fail on an HTTP error (403, 404, 500…): it returns a response withokset tofalse. Always checkresponse.okbefore reading the body, as in the example above.this.fetchAll(url, options)takes the same arguments asfetchand returns the array of all the rows, already parsed. It adds thepagequery parameter itself and requests the pages one after another until it has collectedX-Pagination-Total-Countrows or a page comes back empty. Do not addpageyourself.fetchAllthrows an error if a page answers with an HTTP error, and the whole run stops. Wrap the call intry / catchwhen a list is optional.fetchAllexpects anindexendpoint that answers with an array. Use plainfetchforviewendpoints.fetchAllrequests the pages of one list one after another. To avoid a request per row, load the children of a whole scope with one call and group them in the script (see below).
async function onInit() { const officeId = this.runtime.context.office_id; const result = { equipment: [] }; if (!officeId) { return result; }
try { result.equipment = await this.fetchAll('v2/equipment/index', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filter: { office_id: officeId } }) }); } catch (error) { result.equipment = []; }
return result;}Guidelines
Section titled “Guidelines”- if data is missing, return empty structures (
{},[]) instead of throwing: the template must render anyway; - keep user-facing text in the
template, not in thescript(the script is the same in every language); - when a report has several targets, tell the cases apart with
this.runtime.context.entity_type; - prepare the data in
onInit(filter, group, sort, compute totals) and keep the template for the layout: Handlebars is deliberately poor in logic; - avoid one request per row (for example one
viewfor each person of a list): load the whole list with oneindexfiltered on the scope (office_id,subtenant_id…) and match the rows by id in the script; - filters support operators, for example
{ filter: { work_group_id: { in: [1, 2, 3] } } }.
Template
Section titled “Template”The template is HTML with CSS and Handlebars:
- static content: text, images, layout,
<style>rules (including@pagefor paper size and margins); - dynamic content: expressions such as
{{equipment.name}}, blocks such as{{#each}},{{#if}}, and helpers.
<html> <head> <meta charset='utf-8'> <style> @page { size: A4 portrait; margin: 1.5cm; } table th { font-weight: bold; } </style> </head> <body> <h1>{{equipment.name}}</h1> <p>{{office.name}}</p> <table> <thead> <tr><th>Surname</th><th>Name</th></tr> </thead> <tbody> {{#eachSort equipment.entityEmployee "last_name"}} <tr><td>{{last_name}}</td><td>{{first_name}}</td></tr> {{/eachSort}} </tbody> </table> <p>{{today}}</p> </body></html>See the Handlebars guide for expressions and
built-in helpers (if, unless, each, with…).
Built-in helpers
Section titled “Built-in helpers”4HSE registers these helpers for every report: dateFormat, today, t, eachSort, sum, prod, eq, ne,
lt, gt, lte, gte, and, or, distinct, select, join, qr, logo4hse, eachHcs, hc. The most
common ones:
dateFormat
Section titled “dateFormat”dateFormat(dateString)
Starting from a date in the yyyy-mm-dd format, it returns the date formatted according to the user’s language.
If the value is missing, it prints a blank line (____________) to be filled in by hand, which is handy in printed forms.
{{ dateFormat "2010-10-05" }} // User language: it-IT, returns 05/10/2010t(namespace, key)
Returns a translation of the app in the user’s language, for example a label that is already translated in 4HSE.
{{t "common" "select"}} // User language: it-IT, returns Selezionaqr and logo4hse
Section titled “qr and logo4hse”qr(text) draws a QR code, logo4hse the 4HSE logo. Both return SVG markup, so they must be written with
triple braces, otherwise Handlebars shows the tags as text (see Escaping).
{{{qr verifyUrl}}}{{{logo4hse}}}today()
Returns the current date formatted according to the user’s language.
{{ today }} // 05/10/2020eachSort
Section titled “eachSort”eachSort(context, sortAttribute, direction, options)
Iterates a collection of resources ordered by an attribute in ascending or descending order ("asc" or "desc", ascending
by default). Example: scroll through the entire collection of offices ordering them in ascending order office1, office2 as in the example below.
The attribute can be a path ("person.last_name"). The values are compared as text, so 10 comes before 9:
to sort by a number, sort in onInit. The collection itself is sorted, not a copy.
//offices = [{name: "office3"},{name: "office1"}]{{#eachSort offices "name" "asc"}} {{name}} // office1,office3{{/eachSort}}sum(v1, v2)
Sums v1 and v2. Addition of two numbers that returns a result. If a value is a string, the two are joined
instead ("1" and "2" give "12"): convert the values to numbers in onInit when they come from the API.
{{sum 1 2}} // 3prod(v1, v2)
Multiplication between v1 and v2.
{{prod 3 2}} // 6eq(v1, v2)
Compares if v1 is equal to v2. Returns a boolean value. The comparison is strict: 1 and "1" are different (ne is strict too). Check the type of the values you get from the API before comparing them. lt, gt, lte
and gte compare strings in alphabetical order.
{{eq "1" "2"}} // false{{eq "2" "2"}} // truene(v1, v2)
Compares if v1 is different from v2. Returns a boolean value.
{{ne "1" "2"}} // true{{ne "2" "2"}} // falselt(v1, v2)
Compares if v1 is less than v2. Returns a boolean value.
{{lt "1" "2"}} // true{{lt "2" "2"}} // false{{lt "3" "2"}} // falsegt(v1, v2)
Compares if v1 is greater than v2. Returns a boolean value.
{{gt "1" "2"}} // false{{gt "2" "2"}} // false{{gt "3" "2"}} // truelte(v1, v2)
Compares if v1 is less than or equal to v2. Returns a boolean value.
{{lte "1" "2"}} // true{{lte "2" "2"}} // true{{lte "3" "2"}} // falsegte(v1, v2)
Compares if v1 is greater than or equal to v2. Returns a boolean value.
{{gte "1" "2"}} // false{{gte "2" "2"}} // true{{gte "3" "2"}} // trueand(cond1, cond2, … condN)
Executes a logical AND between two or more conditions. Returns a boolean value.
or(cond1, cond2, … condN)
Executes a logical OR between two or more conditions. Returns a boolean value.
and, or and the comparison helpers return a value, so they are used inside {{#if}} as sub-expressions, in
parentheses:
{{#if (and (gt quantity 0) (eq status "VALID"))}} In use{{/if}}distinct
Section titled “distinct”distinct(list, key)
Starting from a collection, it returns a list of unique resources based on the value of an attribute (key). When several
resources have the same value, the first one is kept.
select
Section titled “select”select(path)
Looks into the current data following a path and keeps only the elements where the last attribute of the path has a value.
In the path, * stands for “each element of the list”. The result is a copy: the original data is not changed.
With officeRisk a list of risks, each with a list riskDemand:
{{select "officeRisk.*.riskDemand.*.probability"}}returns the risks that have at least one riskDemand, and in each risk only the riskDemand where probability is filled.
join(list1, list2, …, listN, key)
Joins two or more collections into one. If the last argument is a string, it is used as distinct does: the elements
with the same value of that attribute appear only once.
{{#each (join people suppliers "id")}} {{name}}{{/each}}In this example, an array based on the officeRisk collection ordered by name is iterated. The iterable array is obtained by combining the distinct, join, and select directives.
{{#eachSort // 1 (distinct // 3 (join // 4 (select "officeRisk.*.riskDemand.*.probability") // 5 (select "officeRisk.*.riskDemand.*.damage") // 6 ) "office_risk_id" // 3 ) "name" // 2}}-
Iterator.
-
Sorts an array of objects by the name attribute.
-
Excludes from iteration all objects with the same office_risk_id (to avoid duplicates).
-
Joins two collections into one.
-
The first collection is
officeRisk. From this collection, it selects only the objects where theofficeRisk.riskDemandattribute is filled andoffice.riskDemand.probabilityis filled. -
The second collection is still
officeRiskbut selects only the objects where theofficeRisk.riskDemandattribute is filled andoffice.riskDemand.damageis filled.
Escaping HTML
Section titled “Escaping HTML”Handlebars turns the characters <, >, & and quotes of every value into text, so that data cannot change the page:
{{description}} shows <b>x</b> as it is written. To print HTML, write the expression with triple braces,
{{{html}}}. Do it only for markup you control (such as the output of qr and logo4hse), never for text entered by
users.
Report-specific helpers
Section titled “Report-specific helpers”Helpers needed by a single report go in its helpers field:
var helpers = { fullName(person) { return person.last_name + ' ' + person.first_name; }}{{ fullName person }}A helper is a function that receives the values written after its name. The last argument is always an options object
added by Handlebars: for a block helper ({{#name}}...{{/name}}) options.fn(context) renders the content of the block.
this is the current context. A helper that returns HTML must wrap it in new Handlebars.SafeString(html), or the
tags are shown as text.
Partials
Section titled “Partials”A partial is a piece of template kept in its own file and included in the report (see Partials for what it is and when to use it).
Declare the partials in partials, mapping the alias (the name used in the template) to the file:
"partials": { "header": { "path": "/projects/<project_id>/templates/header.ht", "name": "header.ht" }}Then include it where you want the piece to appear:
{{> header}}<h1>{{equipment.name}}</h1>How it works:
- the file can be a
.ht, an.htmlor a.hdoc. From a.htonly thetemplateis taken, and its ownscriptandhelpersare not run; from an.htmlor.hdocthe whole content is taken; - the partial is rendered with the data of the place where it is included. It has no data of its own: it uses the keys
returned by the
onInitof the report, so a header that prints{{office.name}}needs a report that returnsoffice; - the partial can use the helpers of the report, but it cannot declare its own;
- the files are read every time the report is generated, so a change to the file is used at the next run;
In the editor, partials are added in the Partials tab: see Report Editor.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.