shift73k/assets_old/node_modules/posthtml-parser
2022-08-13 07:32:36 -04:00
..
.npmignore progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00
.travis.yml progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00
index.js progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00
LICENSE progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00
MAINTAINERS progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00
package.json progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00
README.md progress on migrating to heex templates and font-icons 2022-08-13 07:32:36 -04:00

posthtml-parser

npm version Build Status Coverage Status

Parse HTML/XML to PostHTML AST. More about PostHTML

Install

NPM install

$ npm install posthtml-parser

Usage

Input HTML

<a class="animals" href="#">
    <span class="animals__cat" style="background: url(cat.png)">Cat</span>
</a>
const parser = require('posthtml-parser')
const fs = require('fs')
const html = fs.readFileSync('path/to/input.html').toString()

console.log(parser(html)) // Logs a PostHTML AST

input HTML

<a class="animals" href="#">
    <span class="animals__cat" style="background: url(cat.png)">Cat</span>
</a>

Result PostHTMLTree

[{
    tag: 'a',
    attrs: {
        class: 'animals',
        href: '#'
    },
    content: [
        '\n    ',
            {
            tag: 'span',
            attrs: {
                class: 'animals__cat',
                style: 'background: url(cat.png)'
            },
            content: ['Cat']
        },
        '\n'
    ]
}]

PostHTML AST Format

Any parser being used with PostHTML should return a standard PostHTML Abstract Syntax Tree (AST). Fortunately, this is a very easy format to produce and understand. The AST is an array that can contain strings and objects. Any strings represent plain text content to be written to the output. Any objects represent HTML tags.

Tag objects generally look something like this:

{
    tag: 'div',
    attrs: {
        class: 'foo'
    },
    content: ['hello world!']
}

Tag objects can contain three keys. The tag key takes the name of the tag as the value. This can include custom tags. The optional attrs key takes an object with key/value pairs representing the attributes of the html tag. A boolean attribute has an empty string as its value. Finally, the optional content key takes an array as its value, which is a PostHTML AST. In this manner, the AST is a tree that should be walked recursively.

License

MIT