JavaScript Template Renderer
I'm building a JS template renderer that will take an HTML <template>
element and copy it, along with parsing in any data from a JS object. Text tags are created in HTML using mustache tags such as {{sourceField}}
or {{childObject.sourceField}}
and will be replaced with corresponding values from the data argument.
This template engine will also support a rudimentary IF/ELSEIF/ELSE structure for showing/hiding elements (and it's contents) based on conditions. Condition will be data-value
to match a value directly, data-match
to match on regex, or no value condition which will match if the source value exists.
Example:
-
<div data-if="dataType"></div>
will be displayed ifdataType
exists and is non-empty. -
<div data-if="dataType" data-value="order"></div>
will be displayed if dataType equals order. -
<div data-if="dataType" data-match="^order_\w+"></div>
will be displayed if the dataType matches the regex pattern. -
<div data-elseif="dataType" data-value="product"></div>
will be displayed if the dataType matches product and didn't match previously. -
<div data-else></div>
will match if nothing else in the direct preceding sibling blocks matched.