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

Cannot define custom empty elements for json2html function #37

Open
alanmtk opened this issue Aug 27, 2020 · 0 comments
Open

Cannot define custom empty elements for json2html function #37

alanmtk opened this issue Aug 27, 2020 · 0 comments

Comments

@alanmtk
Copy link

alanmtk commented Aug 27, 2020

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant