Skip to content
This repository was archived by the owner on Apr 10, 2024. It is now read-only.
This repository was archived by the owner on Apr 10, 2024. It is now read-only.

Cannot define custom empty elements for json2html function #37

@alanmtk

Description

@alanmtk

Idea

It would be a nice feature being able to define custom empty elements to be handled by json2html function.

Use case

I am parsing an html block in order to make it amp valid html so among a lot of custom amp tags I have to transform img to amp-img.

Problem

json2html function is handling a predefined list of empty elements:

html2json/src/html2json.js

Lines 125 to 152 in ef49d49

global.json2html = function json2html(json) {
// Empty Elements - HTML 4.01
var empty = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'embed'];
var child = '';
if (json.child) {
child = json.child.map(function(c) {
return json2html(c);
}).join('');
}
var attr = '';
if (json.attr) {
attr = Object.keys(json.attr).map(function(key) {
var value = json.attr[key];
if (Array.isArray(value)) value = value.join(' ');
return key + '=' + q(value);
}).join(' ');
if (attr !== '') attr = ' ' + attr;
}
if (json.node === 'element') {
var tag = json.tag;
if (empty.indexOf(tag) > -1) {
// empty element
return '<' + json.tag + attr + '/>';
}

After parsing my html and modifying the img tag, I want to convert it back to html so I have this situation:

Initial tag:

<img src="example.jpg"/>

Expected result:

<amp-img src="example.jpg"/>

Actual result

<amp-img src="example.jpg"></amp-img>

Proposed solution

Adding an options object to json2html so we can push our custom tags to the predefined list would be enough to make it work.

I made a pull request (#38) with the proposed solution and a test to make sure it works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions