Module:UtilsHTML

From Eco - English Wiki
Revision as of 13:55, 26 February 2022 by Demian (talk | contribs) (Add smaller underline to abbr.)

This module provides utility functions that generate HTML code. They are used to shorten and make code in other modules more readable by providing functions to generate frequently used pieces of HTML code such as an abbr-tag or a unit of measure text like "ppm" (with an abbreviation tag that shows the name of the unit).

Usage

Add the following line of code at the top of your file.

local HTMLUtils = require("Module:UtilsHTML")

-- You may then call functions from this module in your script. For example:
local unitKM = HTMLUtils.tagAbbr("km", "kilometers")

local p = {}

--- Create HTML <code>abbr</code>-tag (abbreviation).
-- @param #string abbreviation The abbreviation (visible text)
-- @param #string title Explanation of the abbreviation (show in tooltip when hovered)
-- @return #string HTML code: "&lt;abbr title="<code>abbreviation</code>"><code>text</code>&lt;/abbr>"
-- @author User:Demian
function p.tagAbbr(abbreviation, title)
	-- Cast to string to avoid errors from using the format string.
	return mw.ustring.format("<abbr style=\"text-decoration: underline dotted 0.0625em;\" title=\"%s\">%s</abbr>", tostring(title), tostring(abbreviation))
end

--- Get the commonly used "ppm" unit as an abbreviation.
--
-- Shorthand for: <code>tagAbbr("ppm", "parts per million")</code>
-- @return #string HTML code for an abbreviation tag with text "ppm" and tooltip "parts per million".
-- @author User:Demian
function p.textUnit_PartsPerMillion()
	-- TODO: Support i18n.
	return p.tagAbbr("ppm", "parts per million")
end

--- Get the commonly used "m/s" (sometimes also "mps") unit as an abbreviation.
--
-- Shorthand for: <code>tagAbbr("m/s", "meters per second")</code>
-- @return #string HTML code for an abbreviation tag with text "m/s" and tooltip "meters per second".
-- @author User:Demian
function p.textUnit_MetersPerSecond()
	-- TODO: Support i18n.
	return p.tagAbbr("m/s", "meters per second")
end

--- Get the commonly used "m" unit as an abbreviation.
--
-- Shorthand for: <code>tagAbbr("m", "meters")</code>
-- @return #string HTML code for an abbreviation tag with text "m" and tooltip "meters".
-- @author User:Demian
function p.textUnit_Meters()
	-- TODO: Support i18n.
	return p.tagAbbr("m", "meters")
end

--- Create HTML code for table with two cells on the same row.
--
-- Intended for displaying two pieces of content side-by-side.
-- @param #string leftCell Content in left cell
-- @param #string rightCell Content in right cell
-- @return #string HTML code for a table with the specified content.
-- @author User:Demian
function p.twoCellTable(leftCell, rightCell)
	return mw.ustring.format("<table><tr><td>%s</td><td>%s</td></tr></table>", leftCell, rightCell)
end

return p