xml-template-literal
v0.4.5
Published
A template literal tag function for parsing xml.
Downloads
39
Readme
xml-template-literal
This library contains a variant-implementation of an LL(1)
parser for parsing xml like structures with intertwined dynamic values.
const ast = xml`
<div class="widget">
<h1>Some Title</h1>
<form>
<input type="text" name="something" />
<input type="submit" onclick=${(ev) => submit(ev)} />
</form>
</div>
`;
Installation
NPM - ESM
import { xml } from 'xml-template-literal';
NPM - UMD
const { xml } = require('xml-template-literal');
CDN - ESM
<script type="module">
import { xml } from 'https://cdn.jsdelivr.net/npm/xml-template-literal/dist/api.js';
</script>
CDN - UMD
<script src="https://cdn.jsdelivr.net/npm/xml-template-literal/legacy/umd.js"></script>
<script>
const { xml } = xmlTemplateLiteral;
</script>
Demos
- Parse and render HTML: https://jsfiddle.net/bq7m4uhw/30/
AST Format & Types
AstRoot
AstRoot
is the type returned by the xml
template literal tag function & the parseXml function call.
type AstRoot<T> = {
kind: AstKind.Root;
children: AstChild<T>[];
}
AstChild
type AstChild<T> = TextChild | DataChild<T> | NodeChild<T>
type TextChild = {
kind: AstKind.Child;
type: ChildType.Text;
value: string;
};
type DataChild<T> = {
kind: AstKind.Child;
type: ChildType.Data;
value: T;
};
type NodeChild<T> = {
kind: AstKind.Child;
type: ChildType.Node;
tag: string;
children: AstChild<T>[];
attributes: AstAttribute<T>[];
};
AstAttribute
type AstAttribute<T> = TextAttribute | DataAttribute<T> | CompositeAttribute<T>;
// key="text_value"
type TextAttribute = {
kind: AstKind.Attribute;
type: AttributeType.Text;
key: string;
value: string;
};
// key=${data_value}
type DataAttribute<T> = {
kind: AstKind.Attribute;
type: AttributeType.Data;
key: string;
value: T;
};
// key="text_value ${data_value}"
type CompositeAttribute<T> = {
kind: AstKind.Attribute;
type: AttributeType.Composite;
key: string;
value: AstAttributeComposite<T>[];
};
AstAttributeComposite
type AstAttributeComposite<T> = TextComposite | DataComposite<T>;
type TextComposite = {
kind: AstKind.Composite;
type: AttributeType.Text;
value: string;
};
type DataComposite<T> = {
kind: AstKind.Composite;
type: AttributeType.Data;
value: T;
};